Generating Secure Random Numbers

Example to generate secure random numbers

package random;

import java.security.SecureRandom;

/**
 * A Simple Example to generate secure random numbers using
 * java.security.SecureRandom class.
 * 
 */
public class SecureRandomGenerator {
  public static void main(String[] args) {

    // Get the instance of SecureRandom class with specified PRNG algorithm
    SecureRandom secureRandom = new SecureRandom();

    // You can use the getInstance() of the Secure Random class to create an object of SecureRandam
    // where you would need to specify the algorithm name.
    // SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");

    // Display the algorithm name
    System.out.println("Used algorithm: " + secureRandom.getAlgorithm());

    // You also specify the algorithm provider in the getInstance() method
    // SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");

    // Display the Provider
    System.out.println("Provider: " + secureRandom.getProvider());

    // A call to the setSeed() method will seed the SecureRandom object.
    // If a call is not made to setSeed(),
    // The first call to nextBytes method will force the SecureRandom object to seed itself.

    // Get 10 random numbers
    System.out.println("Random Integers generated using SecureRandom");
    for (int i = 0; i < 10; i++) {
      System.out.println(secureRandom.nextInt());
    }
  }
}

Why use 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