Versions Compared

Key

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

...

If there is no such a case, a same sequence of random numbers may cause a vulnerability.

Noncompliant Code Example

Compliant Solution

Using  Using a null seed value may prevent such problems. Java's default seed uses system's time in milliseconds. However, you should neither use two different generators with a null seed value nor "resetting" generator's instance more than once (using new Random() multiple times) as you may get identical numbers in the former case and number not actually random in the latter one.

Code Block
bgColor#FFCCCC#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]
   int n = number.nextInt(21);
   System.out.println(n);
}

...

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

Compliant Solution

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

...