How to create an array of 20 random bytes?
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);
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.