Saturday, April 18, 2015

Java Generating Secure Random

SecureRandom class in Java provides cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2. The seed material passed to the random number must be unpredictable. 

A caller obtains a SecureRandom  via a no argument constructor or one of the getInstance methods. 

SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);

Many random number generators are in the form of pseudo - random number generator (PRNG), which means they use deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use combination of these two techniques. 

Also, if the requirement is only to generate a unique identifier which is not securely strong, below approach can be used as well.  

 String uuid = UUID.randomUUID().toString();
 uuid = uuid.replaceAll("-", "z");
 return uuid;

References:

No comments:

Post a Comment