John von Neumann's quote is widely known:
"Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin."
Pseudorandom number generators (PRNGs) use deterministic mathematical algorithms to produce a sequence of numbers with good statistical properties, but the numbers produced are not genuinely random. PRNGs usually start with an arithmetic seed value. The algorithm uses this seed to generate an output value and a new seed as well, which is used to generate the next value, and so on.
...
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);
}
|
...
Code Block | ||
---|---|---|
| ||
import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; // ... public static void main (String args[]) { try { SecureRandom number = SecureRandom.getInstance ("SHA1PRNG"); // generateGenerate 20 integers 0..20 for (int i = 0; i<20i < 20; i++) { System.out.println(number.nextInt(21)); } } catch (NoSuchAlgorithmException nsae) { /* forward // Forward to handler */ } } |
Exceptions
MSC30-EX1: Using a null
seed value (as opposed to reusing it) may improve security marginally but should only be used for non-critical applications. Java's default seed uses the system's time in milliseconds. This exception is not recommended for applications requiring high security (for instance, session IDs should be adequately random). When used, explicit documentation of this exception is encouraged.
Code Block | ||
---|---|---|
| ||
import java.util.Random; // ... Random number = new Random(); int n; //... for (int i=0; i<20; i++) { // reRe-seed generator number = new Random(); // generateGenerate another random integer in the range [0, 20] n = number.nextInt(21); System.out.println(n); } |
...