Java中的SecureRandom getSeed()方法及其示例

这个 getSeed() 方法 JAVA安全安全随机 类用于返回给定数量的种子字节,该字节使用该类用于自身种子的种子生成算法计算。此调用可用于为其他随机数生成器设定种子。

null

此方法仅用于向后兼容。建议调用者使用另一种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]

注:

  1. 以上程序不会在在线IDE上运行。
  2. 每次安全随机类都会生成随机输出。
© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享