How to create an array of 20 random bytes?

2019-02-01 15:05发布

How can I create an array of 20 random bytes in Java?

5条回答
时光不老,我们不散
2楼-- · 2019-02-01 15:44

If you are already using Apache Commons Lang, the RandomUtils makes this a one-liner:

byte[] randomBytes = RandomUtils.nextBytes(20);
查看更多
干净又极端
3楼-- · 2019-02-01 15:45

Java 7 introduced ThreadLocalRandom which is isolated to the current thread.

This is an another rendition of maerics's solution.

final byte[] bytes = new byte[20];
ThreadLocalRandom.current().nextBytes(bytes);
查看更多
我只想做你的唯一
4楼-- · 2019-02-01 15:46

Try the Random.nextBytes method:

byte[] b = new byte[20];
new Random().nextBytes(b);
查看更多
We Are One
5楼-- · 2019-02-01 15:48

Create a Random object with a seed and get the array random by doing:

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]);
查看更多
对你真心纯属浪费
6楼-- · 2019-02-01 15:53

If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom.

Java 6 & 7:

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

Java 8 (even more secure):

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);
查看更多
登录 后发表回答