Home » Core Java » security » Generate a secure random number example

About Byron Kiourtzoglou

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.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

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