Wednesday 10 August 2016

Random String Generator in JAVA in a secure way.

When we make real time applications in JAVA then we need to generate the random strings, e.g 1) for the Session Id of the logged in account
2).  User id

So in JAVA we have mainly two Classes for generating random strings.

1. First one is   Random.
Package -  java.math.Random;

It generate 64 binary bits. And it uses the  System Clock as the seed/or to generate the seed. So it can be reproduced easily if the attacker knows the time at which the seed was generated.


2. Second one is SecureRandom
Package -   java.security.SecureRandom;

It generates 128 binary bits. And it takes Random Data from  Operating System (they can be interval between keystrokes etc. and uses that as the seed.


Comparison

In case of Random just  2^64 attempts are required, and with todays advanced cpu's it is possible to break it in practical time. But for Securerandom   2^128 attempts will be required, which will take years and years to break even with today's advanced machines.
Hence more Secured.

Sample Code :

import java.util.*;
import java.math.*;
import java.security.SecureRandom;

class Sample
{
    public static void main(String[] args)
    {
       
        System.out.println("Random String generator");

        //create the object of the class
        Random random = new Random();
        //calling the function nextInt() for Integer String
        int random_string = random.nextInt();
        System.out.println("Random String: " + random_string);


        SecureRandom secure_random = new SecureRandom();
        //Converting it into Hexadecimal String
        String secure_random_string =new BigInteger(128,secure_random).toString(16);
        System.out.println("Secure random String : " + secure_random_string);

    }
}

OutPut: 
 
Random String: 1679018150
Secure random String : 5b27000e84c8dd8fdebd0d625238499a