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:
- “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.
- 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 | import java.util.Random; |
The output of above code:
1 | -1133938638 |
As shown above, java.util.Random
actually creates pseudorandom numbers which are predictable if algorithm and seed value are known.