Java 中的 SecureRandom nextBytes()方法
可以使用 java.security.SecureRandom 類中的 nextBytes() 方法來獲取使用者指定的隨機位元組數。此方法需要一個引數,即一個隨機位元組陣列,它將返回使用者指定的隨機位元組。
一個演示程式如下所述 -
示例
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: [110, -119, -65, -84, 54]
現在讓我們瞭解一下上面的程式。
nextBytes() 方法用於獲取使用者指定的隨機位元組數。
使用此方法,將在操作前後顯示位元組陣列。一個演示程式碼片段如下 -
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