security

Generate a secure random number example

In this example we shall show you how to generate a secure random number. To generate secure random numbers one should perform the following steps:

  • Create a SecureRandom for the SHA1PRNG algorithm, which is a secure number generator, using the getInstance(String algorithm) API method.
  • Create a new byte array with a specific length (128 in the example).
  • Invoke the nextBytes(byte[] bytes) API method of the SecureRandom, in order to generate the random bytes and fill the byte array.
  • Create two new secure number generators for the SHA1PRNG algorithm. Give the two new generators the same seed, using the generateSeed(int numBytes) API method,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
 
public class GenerateSecureRandomNumber {
 
  public static void main(String[] args) {

    try {
	    
	// Create a secure random number generator using the SHA1PRNG algorithm
	SecureRandom secureRandomGenerator = SecureRandom.getInstance("SHA1PRNG");
	
	// Get 128 random bytes
	byte[] randomBytes = new byte[128];
	secureRandomGenerator.nextBytes(randomBytes);

	// Create two secure number generators with the same seed
	int seedByteCount = 5;
	byte[] seed = secureRandomGenerator.generateSeed(seedByteCount);

	SecureRandom secureRandom1 = SecureRandom.getInstance("SHA1PRNG");
	secureRandom1.setSeed(seed);
	SecureRandom secureRandom2 = SecureRandom.getInstance("SHA1PRNG");
	secureRandom2.setSeed(seed);
	
    } catch (NoSuchAlgorithmException e) {
    }
 
  }
}

 
This was an example of how to generate secure random numbers in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button