Versions Compared

Key

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

...

Consequently, 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.

...

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

Code Block
bgColor#ccccff
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
// ...

public static void main (String args[]) {
   try {
     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) { 
     // Forward to handler
   }
}

...

MSC02-EX0: Using 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 20062014] and may improve security marginally. As a result, it may be used only for noncritical applications operating on nonsensitive data. Java's default seed uses the system's time in milliseconds. When used, explicit documentation of this exception is required.

Code Block
bgColor#ccccff
import java.util.Random;
// ...

Random number = new Random(); // Used only used for demo purposes
int n;
//...
for (int i = 0; i < 20; i++) {
  // Re-seedReseed generator
  number = new Random();
  // Generate another random integer in the range [0, 20]
  n = number.nextInt(21);
  System.out.println(n);
}

For noncritical cases, such as adding some randomness to a game or unit testing, the use of class Random is acceptable. However, it is worth reiterating that the resulting low-entropy random numbers are insufficiently random to be used for more security-critical applications, such as cryptography.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC02-J

highHigh

probableProbable

mediumMedium

P12

L1

Automated Detection

Tool
Version
Checker
Description
Coverity7.5RISKY_CRYPTOImplemented

Related Vulnerabilities

CVE-2006-6969 describes a vulnerability that enables attackers to guess session identifiers, bypass authentication requirements, and conduct cross-site request forgery attacks.

Related Guidelines

SEI CERT C Coding Standard

MSC30-C. Do not use the rand() function for generating pseudorandom numbers

SEI CERT C++ Coding Standard

MSC50-CPP. Do not use std::rand() for generating pseudorandom numbers

MITRE CWE

CWE-327. , Use of a broken or risky cryptographic algorithm Broken or Risky Cryptographic Algorithm
CWE-330. , Use of insufficiently random values

 

Insufficiently Random Values
CWE-332
. , Insufficient entropy Entropy in PRNG 
CWE-336
. , Same seed Seed in PRNG 
CWE-337
. , Predictable seed Seed in PRNG

Bibliography

 

 

...