# Random vs Secure Random numbers in Java

Java 8Object Oriented ProgrammingProgramming

Java provides two classes for having random numbers generation - SecureRandom.java and Random.java.The random numbers can be used generally for encryption key or session key or simply password on web server.SecureRandom is under java.security package while Random.java comes under java.util package.The basic and important difference between both is SecureRandom generate more non predictable random numbers as it implements Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) as compare to Random class which uses Linear Congruential Generator (LCG).

A important point to mention here is SecureRandom is subclass of Random class and inherits its all method such as nextBoolean(),nextDouble(),nextFloat(),nextGaussian(),nextInt() and nextLong().

Other differences between Random and SecureRandom includes −

• Random class uses system time for its generation algorithm as input while SecureRandom class uses random data from operating system such as timing of I/O events.

• Due to complex algorithm used in case of SecureRandom which make it more unpredictable,it takes more memory consumption in create secure random numbers than random numbers.

• Random class has only 48 bits where as SecureRandom can have upto 128 bits which makes the probability of repeating in SecureRandom are smaller.Due to this also the number of attempts to break Random number prediction comes to 2^48 while that of SecureRandom number is 2^128 which again makes it more secure.

## Example Random number Generation

Live Demo

import java.util.Random;
public class RandomClass {
public static void main(String args[]) {
Random objRandom = new Random();
int randomInt1 = objRandom.nextInt(1000);//1000 is range i.e number to be generated would be          between 0 and 1000.
int randonInt2 = objRandom.nextInt(1000);
System.out.println("Random Integers: " + randomInt1);
System.out.println("Random Integers: " + randonInt2);
}
}

## Output

Random Integers: 459
Random Integers: 348

## Example SecureRandom number Generation

Live Demo

import java.security.SecureRandom;
public class SecureRandomClass {
public static void main(String args[]) {
SecureRandom objSecureRandom = new SecureRandom();
int randomInt1 = objSecureRandom.nextInt(1000);
int randonInt2 = objSecureRandom.nextInt(1000);
System.out.println("Random Integers: " + randomInt1);
System.out.println("Random Integers: " + randonInt2);
}
}

## Output

Random Integers: 983
Random Integers: 579
Published on 01-Nov-2018 11:06:52