 
                            ...
| Code Block | ||
|---|---|---|
| 
 | ||
| import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
// ...
public static void main (String args[]) {
  SecureRandom number = new SecureRandom();
  // Generate 20 integers 0..20
  for (int i = 0; i < 20; i++) {
    System.out.println(number.nextInt(21));
  }
}
 | 
Compliant Solution (Java 8)
This compliant solution uses the SecureRandom.getInstanceStrong() method, introduced in Java 8, to use a strong RNG algorithm, if one is available.
| Code Block | ||
|---|---|---|
| 
 | ||
| import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; // ... public static void main (String args[]) { try { SecureRandom number = SecureRandom.getInstancegetInstanceStrong(); // Generate 20 integers 0..20 for (int i = 0; i < 20; i++) { System.out.println(number.nextInt(21)); } } catch (NoSuchAlgorithmException nsae) { // Forward to handler } } | 
Exceptions
MSC02-J-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 2014] 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.
...