In computer applications, sometimes we require to generate and use random numbers but its important to understand the degree of randomness in the method of generating random numbers. Typically there are two types of random number generators, pseudo random number generators and secure random number generators. Lets see the difference between the two types.
Pseudo random generators
A pseudo random number generator uses computer algorithms/mathematical formulas to produce random numbers. It might seem strange, but its very difficult to generate pure random numbers using computer algorithms alone. Computer follows set of instructions given to it blindly which means its output are completely predictable. Two instance of generator will perform the exact same set of steps each time and if the initial state/seed value to the pseudorandom generators, they will produce the same set of numbers. PRNG sequences will appear to be random and will pass statical tests but are not truly random and not cryptographically secure.
Java code for generating pseudo random numbers
import java.util.Random;
public class TestRandom
{
public static void main(final String[] args)
{
long seed = 12345678;
Random r = new Random(seed);
for (int i = 0; i< 5; i++) {
System.out.println(r.nextInt());
}
}
}
This produces same sequence of numbers every time the program is run.
Secure random generators
True random numbers can be produced by taking into accounts some random physical activity/ hardware events like keyboard event, interrupts etc. This is what secure random number generators do. They also include some entropy along with algorithms. This mean even with same initial state/seed value, a different sequence of random numbers will be produced. These are truly random and cryptographically secure.
Java code for generating secure random numbers
import java.security.SecureRandom;
public class TestSecureRandom
{
public static void main(final String[] args)
{
String seed = "12345678";
SecureRandom r = new SecureRandom(seed.getBytes());
for (int i = 0; i< 5; i++) {
System.out.println(r.nextInt());
}
}
}
This produces new/random sequence of numbers every time program is run.
Comparison
Pseudo Random Generator | Secure Random Generator | |
Methodology | Mathematical formula like Linear Congruential | Involve some physical randomness |
Efficiency | More efficient | Less efficient |
Deterministic (can be reproduced at later time) | Yes | No |
Periodic (sequence repeats itself) | Yes | No |
Applications | Simulation and modelling, statistical purposes | Cryptography |