...
If you use the same seed value, you will always get the same sequence of numbers; thus they will not be so "random."
Code Block | ||
---|---|---|
| ||
import java.util.Random; // ... Random number = new Random(123L); //... for (int i=0; i<20; i++) { // generate another random integer in the range [0,20] int n = number.nextInt(21); System.out.println(n); } |
There are cases of course, where the same sequence of random numbers is desirable, such as regression tests of program behavior. Otherwise, generating the same sequence of random numbers may cause a vulnerability.
Compliant Solution
Using a null seed value may prevent such problems. Java's default seed uses the system's time in milliseconds.
...
Code Block | ||
---|---|---|
| ||
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
// ...
public static void main (String args[])
{
try
{
static SecureRandom number = SecureRandom.getInstance ("SHA1PRNG");
// ...
// generate 20 integers 0..20
for (int i=0; i<20; i++)
{
System.out.println(number.nextInt(21));
}
}
catch (NoSuchAlgorithmException nsae) {}
}
|
...