HmacDrbg implements Drbg { @Override public synchronized void nextBytes(byte[] bytes) { int pos = 0; while (pos < bytes.length) { this.val = this.mac.doFinal(this.val); int length = val.length; if (length > bytes.length - pos) { length = bytes.length - pos; } System.arraycopy(val, 0, bytes, pos, length); pos += length; } update(null); this.reseedCounter++; if (this.reseedCounter >= MAX_RESEED_COUNT) { if (this.seeds.isEmpty()) { throw new IllegalStateException( "No more seeds available. Security guarantees no longer holds. " + "Please restart the application using more seeds to continue beyond this point."); } setSeed(this.seeds.remove(0)); } } HmacDrbg(byte[]... seeds);  HmacDrbg(Supplier<Mac> macSupplier, byte[]... seeds); @Override synchronized void nextBytes(byte[] bytes);  }
@Test public void testNextBytes() throws NoSuchAlgorithmException { byte[] bytes = new byte[]{0x10, 0x09, 0x01}; HmacDrbg rand1 = new HmacDrbg(bytes); HmacDrbg rand2 = new HmacDrbg(bytes); HmacDrbg rand3 = new HmacDrbg(); byte[] randBytes1 = new byte[10]; byte[] randBytes2 = new byte[10]; byte[] randBytes3 = new byte[10]; rand1.nextBytes(randBytes1); rand2.nextBytes(randBytes2); rand3.nextBytes(randBytes3); assertArrayEquals(randBytes1, randBytes2); assertFalse(Arrays.equals(randBytes1, randBytes3)); }
@Test public void testDifferentAlgorithm() throws NoSuchAlgorithmException { byte[] bytes = new byte[]{0x10, 0x09, 0x01}; HmacDrbg rand1 = new HmacDrbg(bytes); HmacDrbg rand2 = new HmacDrbg(new Supplier<Mac>() { @Override public Mac get() { try { return Mac.getInstance("HmacSHA512"); } catch (NoSuchAlgorithmException e) { return null; } } }, bytes); byte[] randBytes1 = new byte[10]; byte[] randBytes2 = new byte[10]; rand1.nextBytes(randBytes1); rand2.nextBytes(randBytes2); assertFalse(Arrays.equals(randBytes1, randBytes2)); }
@Test(expected = IllegalStateException.class) public void testReseedException() throws NoSuchAlgorithmException { HmacDrbg m = new HmacDrbg(new byte[]{0x01}); m.reseedCounter = HmacDrbg.MAX_RESEED_COUNT - 1; double max = 2; for (double i = 0; i < max; i++) { byte[] randBytes1 = new byte[0]; m.nextBytes(randBytes1); } }
@Test(expected = IllegalStateException.class) public void testReseedException2() throws NoSuchAlgorithmException { HmacDrbg m = new HmacDrbg(new byte[]{0x01}, new byte[]{0x02}); m.reseedCounter = HmacDrbg.MAX_RESEED_COUNT - 1; byte[] randBytes1 = new byte[0]; for (double i = 0; i < 2; i++) { m.nextBytes(randBytes1); } m.reseedCounter = HmacDrbg.MAX_RESEED_COUNT - 1; for (double i = 0; i < 2; i++) { m.nextBytes(randBytes1); } }
@Test public void testLargeAmount() throws NoSuchAlgorithmException { byte[] bytes = new byte[]{0x10, 0x09, 0x01}; HmacDrbg rand1 = new HmacDrbg(bytes); HmacDrbg rand2 = new HmacDrbg(bytes); byte[] randBytes1 = new byte[1000000]; byte[] randBytes2 = new byte[1000000]; rand1.nextBytes(randBytes1); rand2.nextBytes(randBytes2); assertArrayEquals(randBytes1, randBytes2); }