...
This noncompliant code example uses the insecure java.util.Random class. This class produces an identical sequence of numbers for each given seed value; consequently, the sequence of numbers is predictable.
| Code Block | ||
|---|---|---|
| ||
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);
}
|
...
This compliant solution uses the java.security.SecureRandom class to produce high-quality random numbers.
| Code Block | ||
|---|---|---|
| ||
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 2006] 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 | ||
|---|---|---|
| ||
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);
}
|
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
MSC02-J | high | probable | medium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description |
|---|---|---|---|
| Coverity | 7.5 | RISKY_CRYPTO | Implemented |
Related Vulnerabilities
Related Guidelines
MSC30-C. Do not use the rand() function for generating pseudorandom numbers | |
MSC30-CPP. Do not use the rand() function for generating pseudorandom numbers | |
CWE-327. Use of a broken or risky cryptographic algorithm | |
| CWE-330. Use of insufficiently random values |
| CWE-332. Insufficient entropy in PRNG |
| CWE-336. Same seed in PRNG |
| CWE-337. Predictable seed in PRNG |
...