簡體   English   中英

如何創建一個包含 20 個隨機字節的數組?

[英]How to create an array of 20 random bytes?

如何在 Java 中創建一個包含 20 個隨機字節的數組?

嘗試Random.nextBytes方法:

byte[] b = new byte[20];
new Random().nextBytes(b);

如果您想要一個不使用第三方 API 的加密強隨機數生成器(也是線程安全的),您可以使用SecureRandom

Java 6 和 7:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Java 8(更安全):

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

如果您已經在使用 Apache Commons Lang,那么RandomUtilsRandomUtils單行:

byte[] randomBytes = RandomUtils.nextBytes(20);

注意:這不會產生加密安全的字節。

Java 7 引入了與當前線程隔離的ThreadLocalRandom

這是maerics 解決方案的另一種演繹。

final byte[] bytes = new byte[20];
ThreadLocalRandom.current().nextBytes(bytes);

創建一個帶有種子的Random對象並通過執行以下操作獲取數組隨機:

public static final int ARRAY_LENGTH = 20;

byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);

對於那些想要更安全的方式來創建隨機字節數組的人來說,是的,最安全的方式是:

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

但是,如果機器上沒有足夠的隨機性,您的線程可能會阻塞,具體取決於您的操作系統。 以下解決方案不會阻塞:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

這是因為第一個示例使用/dev/random並且會在等待更多隨機性(由鼠標/鍵盤和其他來源生成)時阻塞。 第二個示例使用不會阻塞的/dev/urandom

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM