SecureRandom generateSeed() method in Java


The number of seed bytes can be obtained using the method generateSeed() in class java.security.SecureRandom. This method requires a single parameter i.e. the number of seed bytes and it returns the seed bytes that are generated.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.security.*;
import java.util.*;
public class Demo {
   public static void main(String[] argv) {
      try {
         SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
         byte[] arrB = sRandom.generateSeed(5);
         System.out.println("The seed bytes generated are: " + Arrays.toString(arrB));
      } catch (NoSuchAlgorithmException e) {
         System.out.println("Error!!! NoSuchAlgorithmException");
      }
   }
}

Output

The seed bytes generated are: [16, -115, 126, -30, 39]

Now let us understand the above program.

The method generateSeed() is used to obtain the required number of seed bytes in a byte array arrB[]. Then the seed bytes are displayed. If the algorithm is wrong, then the exception of NoSuchAlgorithmException is thrown. A code snippet that demonstrates is given as follows −

try {
   SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
   byte[] arrB = sRandom.generateSeed(5);
   System.out.println("The seed bytes generated are: " + Arrays.toString(arrB));
} catch (NoSuchAlgorithmException e) {
   System.out.println("Error!!! NoSuchAlgorithmException");
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements