Java SecureRandom getSeed()方法及示例

来源:这里教程网 时间:2026-02-17 21:08:37 作者:

Java SecureRandom getSeed()方法及示例

java.security.SecureRandom 类的 getSeed() 方法用于返回给定的种子字节数,该字节数是使用该类用来给自己播种的种子生成算法计算的。这个调用可以用来给其他随机数生成器添加种子。

这个方法只是为了向后兼容而包含。我们鼓励调用者使用另一种getInstance方法来获得SecureRandom对象,然后调用generateSeed方法来从该对象获得种子字节。

语法

public static byte[] getSeed(int numBytes)

参数: 该方法将种子字节的数量作为生成的参数。

返回值: 该方法返回种子字节。

下面是说明getSeed()方法的例子。

例子 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);        }    }}

输出

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

例子 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);        }    }}

输出

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

注意

    上述程序不会在在线IDE上运行。每次安全随机类都会产生随机输出:

相关推荐