Java中的 SecureRandom generateSeed() 方法及示例
Java.security.SecureRandom类的generateSeed()方法用于返回给定数量的种子字节,使用此类用于为自身播种的种子生成算法计算得出。此调用可用于播种其他随机数生成器。
句法:
public byte[] generateSeed(int numBytes)
参数:此方法将要生成的种子字节数作为参数。
返回值:此方法返回生成的种子字节。
下面是说明generateSeed()方法的示例:
笔记:
- 该程序不会在在线 IDE 上运行。
- 每次 Secure Random 类都会产生随机输出。
示例 1:
Java
// Java program to demonstrate
// generateSeed() 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 generated seed by into byte array
// by using method generateSeed()
byte[] arr = sr.generateSeed(8);
// printing the byte array
System.out.println(Arrays.toString(arr));
}
catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Java
// Java program to demonstrate
// generateSeed() method
import java.security.*;
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
// creating the object of SecureRandom getting the instance of TAJMAHAL
System.out.println("Trying to get the instance from an unknown source");
SecureRandom sr = SecureRandom.getInstance("TAJMAHAL");
// getting the generated seed by into byte array
// by using method generateSeed()
byte[] arr = sr.generateSeed(5);
// printing the byte array
System.out.println("Seed Bytes: " + Arrays.toString(arr));
}
catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
[24, -16, -12, 25, -3, 66, -90, 103]
示例 2:
Java
// Java program to demonstrate
// generateSeed() method
import java.security.*;
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
// creating the object of SecureRandom getting the instance of TAJMAHAL
System.out.println("Trying to get the instance from an unknown source");
SecureRandom sr = SecureRandom.getInstance("TAJMAHAL");
// getting the generated seed by into byte array
// by using method generateSeed()
byte[] arr = sr.generateSeed(5);
// printing the byte array
System.out.println("Seed Bytes: " + Arrays.toString(arr));
}
catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Trying to get the instance from an unknown source
Exception thrown : java.security.NoSuchAlgorithmException: TAJMAHAL SecureRandom not available