Why use Secure Random Numbers

Have you ever thought, how random is our random number generator. For security purposes, it is very necessary that we use an API that helps us generate random numbers that are unique in nature and cannot be guessed easily. If the random numbers that we use in our application is can be guessed, it creates a loophole in the security of the application.

Java provides 2 classes for generating random numbers:

  • java.util.Random
  • java.security.SecureRandom

Random:

As mentioned in the Javadocs: “An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula”. And it’s also mentioned in the Javadocs that “If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers”.

By default, the seed for the Random algorithm is the system time in milliseconds, making the random numbers guessable.

SecureRandom:

“This class provides a cryptographically strong pseudo-random number generator (PRNG)”, as mentioned in the Javadocs. Since the random numbers generated by this class are cryptographically secure, it makes the random numbers non guessable and random in true sense.

It is also important to consider, in which areas of the application we should use SecureRandom class, as the SecureRandom class lowers the performance of the application. But where the security of the application is in question, for example; generating the sessionIds, we must always use the SecureRandom class.

Example to generate secure random numbers

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s