当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java SecureRandom generateSeed()用法及代码示例


java.security.SecureRandom类的generateSeed()方法用于返回给定数量的种子字节,该种子字节数是使用此类用于自身播种的种子生成算法进行计算的。此调用可用于为其他随机数生成器提供种子。

用法:

public byte[] generateSeed(int numBytes)

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


返回值:此方法返回生成的种子字节。

下面是说明generateSeed()方法的示例:

注意:

  1. 该程序将无法在在线IDE上运行。
  2. 每次Secure Random类将生成随机输出。

示例1:

// 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"); 
  
            // geting the genrated 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); 
        } 
    } 
}

输出:

[24, -16, -12, 25, -3, 66, -90, 103]

示例2:

// 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


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 SecureRandom generateSeed() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。