當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。