Java 中的 SecureRandom getInstance() 方法
SecureRandom 物件可以使用類 java.security.SecureRandom 中的 getInstance() 方法獲取。這個 SecureRandom 物件有助於實現指定的隨機數生成器 (RNG) 演算法。
getInstance() 方法需要一個引數,即隨機數生成器 (RNG) 演算法,並返回 SecureRandom 物件。
下面給出了展示此方法的程式 −
範例
import java.security.*;
import java.util.*;
public class Demo {
public static void main(String[] argv) {
try {
SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
String s = "Apple";
byte[] arrB = s.getBytes();
System.out.println("The Byte array before the operation is: " + Arrays.toString(arrB));
sRandom.nextBytes(arrB);
System.out.println("The Byte array after the operation is: " + Arrays.toString(arrB));
} catch (NoSuchAlgorithmException e) {
System.out.println("Error!!! NoSuchAlgorithmException");
} catch (ProviderException e) {
System.out.println("Error!!! ProviderException");
}
}
}輸出
The Byte array before the operation is: [65, 112, 112, 108, 101] The Byte array after the operation is: [10, 60, 119, -12, -103]
現在讓我們來理解一下上面的程式。
getInstance() 方法用於獲取 SecureRandom 物件 sRandom。透過它,並在操作前後顯示位元組陣列。下面給出了展示程式碼片段 −
try {
SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
String s = "Apple";
byte[] arrB = s.getBytes();
System.out.println("The Byte array before the operation is: " + Arrays.toString(arrB));
sRandom.nextBytes(arrB);
System.out.println("The Byte array after the operation is: " + Arrays.toString(arrB));
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP