How To Generate Java Pseudo-Random Number

Posted on November 8, 2012. Filed under: java/j2EE |


 

The following is the code example of generating pseudo random number with SecureRandom class.

RandomNumber#mkdir randomnum
RandomNumber#cd randomnum/
RandomNumber#vi PseudoRandomExample.java
RandomNumber#cat PseudoRandomExample.java
import java.security.*;
import java.util.Arrays;
public class PseudoRandomExample {
public static void main(String [] args) {
SecureRandom sr = new SecureRandom();
//Default algorithm depends on OS
System.out.println(sr.getAlgorithm());
//therefore, we want to specify the algorithm.
try {
sr = SecureRandom.getInstance(“SHA1PRNG”);
System.out.println(sr.getAlgorithm());
//sr.setSeed(sr.generateSeed(10)); //hacker can guess seed
byte[] rand1 = new byte[5];
byte[] rand2 = new byte[12];
sr.nextBytes(rand1);
sr.nextBytes(rand2);
System.out.println(Arrays.toString(rand1));
System.out.println(Arrays.toString(rand2));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}

}

RandomNumber#javac PseudoRandomExample.java
RandomNumber#java PseudoRandomExample
NativePRNG
SHA1PRNG
[76, -118, -121, -45, -34]
[27, 107, 121, -25, -27, 23, 33, -84, -40, 124, 23, -74]
RandomNumber#java PseudoRandomExample
NativePRNG
SHA1PRNG
[-54, -58, -64, -77, -14]
[43, 41, -53, -93, -92, -112, -49, 72, 89, -11, 19, -91]
RandomNumber#java PseudoRandomExample
NativePRNG
SHA1PRNG
[-126, -125, 105, 114, -54]
[-54, -94, -71, 4, -96, 76, -20, 72, 100, -72, -65, -80]
RandomNumber#

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: