在Java中,我们可以使用SecureRandom.nextBytes(byte[] bytes)
生成用户指定数量的随机字节。 此SecureRandom
是加密安全的随机数生成器(RNG)。
1.随机的12个字节(96位)
1.1生成一个随机的12字节(96位)随机数。
HelloCryptoApp.java
package com.mkyong.crypto;
import java.security.SecureRandom;
public class HelloCryptoApp {
public static void main(String[] args) {
byte[] nonce = new byte[12];
new SecureRandom().nextBytes(nonce);
System.out.println(convertBytesToHex(nonce));
}
// util to print bytes in hex
private static String convertBytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte temp : bytes) {
result.append(String.format("%02x", temp));
}
return result.toString();
}
}
输出量
Terminal
0747a9ad467d4dc29ce70344
1.2随机产生20个字节(160位)
byte[] nonce = new byte[20];
new SecureRandom().nextBytes(nonce);
System.out.println(convertBytesToHex(nonce));
输出量
Terminal
e2ac8893b23ef174461e4ec37598080ec910b87b
2.随机32字节(256位)+ DRBG算法
2.1使用NIST SP 800-90Ar1中定义的DRBG
算法生成一个随机的32字节(256位)。 默认情况下, SecureRandom
使用SHA1PRNG
算法生成一个随机数。
HelloCryptoApp2.java
package com.mkyong.java11;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class HelloCryptoApp2 {
public static void main(String[] args) throws NoSuchAlgorithmException {
byte[] nonce = new byte[32];
SecureRandom rand = SecureRandom.getInstance("DRBG");
rand.nextBytes(nonce);
System.out.println(convertBytesToHex(nonce));
}
private static String convertBytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte temp : bytes) {
result.append(String.format("%02x", temp));
}
return result.toString();
}
}
输出量
Terminal
7d5bca7a4cfab6abec28da5cc899c32a0c36f17128f242a3df20301b3812b881
进一步阅读
有关所有受支持的随机算法,请参阅此SecureRandom编号生成算法
参考文献
翻译自: https://mkyong.com/java/java-how-to-generate-a-random-12-bytes/