How to create an array of 20 random bytes?

JavaArraysRandom

Java Problem Overview


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

Java Solutions


Solution 1 - Java

Try the Random.nextBytes method:

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

Solution 2 - Java

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

Solution 3 - Java

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

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

Note: this does not produce cryptographically-secure bytes.

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

For those wanting a more secure way to create a random byte array, yes the most secure way is:

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

BUT your threads might block if there is not enough randomness available on the machine, depending on your OS. The following solution will not block:

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

This is because the first example uses /dev/random and will block while waiting for more randomness (generated by a mouse/keyboard and other sources). The second example uses /dev/urandom which will not block.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnovicePrgrmrView Question on Stackoverflow
Solution 1 - JavamaericsView Answer on Stackoverflow
Solution 2 - JavaDavidRView Answer on Stackoverflow
Solution 3 - JavaDuncan JonesView Answer on Stackoverflow
Solution 4 - JavaJin KwonView Answer on Stackoverflow
Solution 5 - JavaΦXocę 웃 Пepeúpa ツView Answer on Stackoverflow
Solution 6 - JavaTom HageView Answer on Stackoverflow