Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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
bgColor#FFCCCC
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
bgColor#ccccff
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) {}
}

...