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));
}

更新於: 30-7-2019

331 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.