Generate Cryptographically Random Data
suggest changeTo generate samples of cryptographically random data:
import java.security.SecureRandom;
import javax.xml.bind.DatatypeConverter;
final byte[] sample = new byte[16];
new SecureRandom().nextBytes(sample);
System.out.println("Sample: " + DatatypeConverter.printHexBinary(sample));
Produces output similar to:
Sample: E4F14CEA2384F70B706B53A6DF8C5EFE
Note that the call to nextBytes() may block while entropy is gathered, depending on the algorithm being used. javax.xml.bind.DatatypeConverter was removed from the JDK in Java 11.
To specify the algorithm and provider:
final byte[] sample = new byte[16];
final SecureRandom randomness = SecureRandom.getInstance("SHA1PRNG", "SUN");
randomness.nextBytes(sample);
System.out.println("Provider: " + randomness.getProvider());
System.out.println("Algorithm: " + randomness.getAlgorithm());
System.out.println("Sample: " + DatatypeConverter.printHexBinary(sample));
Produces output similar to:
Provider: SUN version 1.8
Algorithm: SHA1PRNG
Sample: C80C44BAEB352FD29FBBE20489E4C0B9
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents