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.