如何创建一个20个随机字节的数组?

如何在 Java 中创建一个包含20个随机字节的数组?

122286 次浏览

试试 Random.nextBytes方法:

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

如果您已经在使用 Apache Commons Lang,那么 RandomUtils会将其简化为一行程序:

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

注意: 这不会产生加密安全的字节。

创建一个带有种子的 随机对象,通过以下操作获得随机数组:

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

Java7引入了 ThreadLocalRandom,即 与当前线程隔离的

这是 Merics 的解决方案的另一个版本。

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

如果希望在不使用第三方 API 的情况下使用加密强随机数生成器(也是线程安全的) ,可以使用 SecureRandom

Java8(比以前的版本更安全) :

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

爪哇6及7:

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

对于那些想要更安全地创建随机字节数组的人来说,是的,最安全的方法是:

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