Open In App

SecureRandom getSeed() method in Java with Examples

Last Updated : 04 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

The getSeed() method of java.security.SecureRandom class is used to return the given number of seed bytes, computed using the seed generation algorithm that this class uses to seed itself. This call may be used to seed other random number generators.

This method is only included for backward compatibility. The caller is encouraged to use one of the alternative getInstance methods to obtain a SecureRandom object, and then call the generateSeed method to obtain seed bytes from that object.

Syntax:

public static byte[] getSeed(int numBytes)

Parameters: This method takes the number of seed bytes as a parameter to generate.

Return Value: This method returns the seed bytes.

Below are the examples to illustrate the getSeed() method:

Examples 1:




// Java program to demonstrate
// getSeed() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating the object of SecureRandom
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
  
            // getting the Provider of the SecureRandom sr
            // by using method getSeed()
            byte[] bb = sr.getSeed(5);
  
            // printing the byte array
            System.out.println("Seed Bytes : " + Arrays.toString(bb));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Seed Bytes : [1, 2, 3, 4, 1]

Examples 2:




// Java program to demonstrate
// getSeed() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating the object of SecureRandom
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
  
            // getting the Provider of the SecureRandom sr
            // by using method getSeed()
            byte[] bb = sr.getSeed(10);
  
            // printing the byte array
            System.out.println("Seed Bytes : " + Arrays.toString(bb));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Seed Bytes : [-64, 79, 82, -118, -97, -95, -80, -101, -40, 12]

Note:

  1. The above programs will not run on online IDE.
  2. Every time Secure Random class will generate random output.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads