Random Numbers in Java

Random Numbers in Java

1. Why we need random numbers

Random numbers are used to create an unpredictable result for the purpose of gambling or computer games. Besides, randomness is also important for cryptography. In this case, people generate random numbers that attackers can not guess.

2. Two types of random numbers

There are two types of random numbers:

  1. “true” random numbers:
    • To generate a “true” random number, the computer measures some type of physical phenomenon that takes place outside of the computer. For example, the computer could use the exact time you press keys on your keyboard as a source of unpredictable data, or entropy. In this case, your computer might notice that you pressed a key at exactly 0.31415926 seconds after 2 p.m.. Grab enough of the specific times associated with these key presses and you’ll have a source of entropy you can use to generate a “true” random number. You’re not a predictable machine, so an attacker can’t guess the precise moment when you press these keys.
    • On Linux, dev/random can produce randomness using environmental noise. It’s a random number generator you can type the command in your terminal: head -c 200 /dev/random > random.txt, which can obtain the first 200 characters (bytes) from /dev/random. /dev/random should be suitable for uses that need very high quality randomness such as one-time pad or key generation. When the entropy pool is empty, reads from /dev/random will block until additional environmental noise is gathered.
  2. pseudo-random numbers:
    • A computer could use a seed value and an algorithm to generate numbers that appear to be random, but that are in fact predictable. In these cases, the computer doesn’t gather any random data from the environment.

3. Java generate pseudorandom numbers

Here is an simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Random;

public class RandomDemo {
public static void main(String[] args) {
//initialize two random number generators
// random1 and random2 use same seed
Random random1 = new Random(200);
Random random2 = new Random();
random2.setSeed(200);

System.out.println(random1.nextInt());
System.out.println(random1.nextInt());

System.out.println("---------------");

System.out.println(random2.nextInt());
System.out.println(random2.nextInt());
}
}

The output of above code:

1
2
3
4
5
-1133938638
-1006582214
---------------
-1133938638
-1006582214

As shown above, java.util.Random actually creates pseudorandom numbers which are predictable if algorithm and seed value are known.