English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Random numbers and secure random numbers in Java

Java provides two classes for generating random numbers-SecureRandom.java and Random.java. Random numbers are usually used for encryption keys or session keys on web servers or simply used as passwords. SecureRandom is under the java.security package, while Random.java is located between them. The basic and important difference between the two is that, compared with the Random class that uses a linear congruential generator (LCG), SecureRandom implements a cryptographically secure pseudo-random number generator (CSPRNG), thus generating more unpredictable random numbers.

An important point to mention here is that SecureRandom is a subclass of the Random class, and inherits all its methods, such asnextBoolean(), nextDouble(), nextFloat(), nextGaussian(), nextInt(), andnextLong().

Other differences between Random and SecureRandom include-

  • The Random class uses the system time as input to its generation algorithm, while the SecureRandom class uses the operating system's random data (such as I / O event timing).

  • Since complex algorithms are used in the SecureRandom case, it becomes more unpredictable, so more memory is needed to create secure random numbers than on random numbers.

  • The Random class has only48bits, of which SecureRandom can have at most128bits, which makes the repetition possibility in SecureRandom even smaller, so the number of attempts to break the random number prediction is2 ^ 48, whereas the SecureRandom number is2 ^ 128to make it even more secure.

Example of Random Number Generation

import java.util.Random;
public class RandomClass {
   public static void main(String args[]) {
      Random objRandom = new Random();
      int randomInt1 = objRandom.nextInt(1000);//1000 is the range, i.e. the 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 Result

Random Integers: 459
Random Integers: 348

Example of SecureRandom Number Generation

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 Result

Random Integers: 983
Random Integers: 579