...
The Java API provides a PRNG, the java.util.Random
class. This PRNG is portable and repeatable. Consequently, two instances of the java.util.Random
class that are created using the same seed will generate identical sequences of numbers in all Java implementations. Seed values are often reused on application initialization or after every system reboot. In other cases, the seed is derived from the current time obtained from the system clock. An adversary can learn the value of the seed by performing some reconnaissance on the vulnerable target, and can then build a lookup table for estimating future seed values.
Consequently, it is forbidden to use the java.util.Random
class must not be used either for security-critical applications or for protecting sensitive data. Use a more secure random number generator, such as the java.security.SecureRandom
class instead.
Noncompliant Code Example
...
Exceptions
MSC02-EX1: Using a null
seed value (as opposed to reusing it) the default constructor for java.util.Random
applies a seed value that is "very likely to be distinct from any other invocation of this constructor" (API 2006), and may improve security marginally but should . Therefore, it may only be used for non-critical applications operating on non-sensitive data. Java's default seed uses the system's time in milliseconds. This exception is inapplicable for applications requiring high security (for instance, session IDs should be adequately random). When used, explicit documentation of this exception is encouragedrequired.
Code Block | ||
---|---|---|
| ||
import java.util.Random;
// ...
Random number = new Random(); // only used for demo purposes
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);
}
|
...