Versions Compared

Key

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

It is widely known John von Neumann's quote is widely known:

 "Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin."

Pseudorandom number generators (PRNGs) use deterministic mathematical algorithms  to produce a sequence of numbers with good statistical properties, but the numbers produced are not genuinely random. PRNGs usually start with an arithmetic seed value. The algorithm uses this seed in order to generate an output value and a new seed as well, which is going to be used to generate the next value, and so on.

The Java API provides a PRNG, the java.util.Random class. This PRNG built is portable and repeatable. As a consequence of that, if two Random instances are created using the same seed, they will generate identical sequences of numbers in all Java implementations.

Noncompliant Code Example

In case If you use the same seed value, you will always get the same sequence of numbers, ; thus they will not be so "random." ones.

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, e.g. such as regression tests of program behavior. If there is no such a case, a Otherwise, generating the same sequence of random numbers may cause a vulnerability.

...

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.util.Random;
// ...

Random number = new Random();
int n;
//...
for (int i=0; i<20; i++)
{
   // re-seed generator
   number = new Random();
   // generate another random integer in the range [0,20]
   n = number.nextInt(21);
   System.out.println(n);
}


For non-critical noncritical cases, e.g. such as adding some randomness to a game, the Random class is considered fine. However, it is not random enough to be used by more serious applications, e.g. such as cryptography.

Compliant Solution

This compliant solution uses uses the java.security.SecureRandom class in order to produce high quality random numbers.

...