How to create an array of 20 random bytes?
Try the Random.nextBytes
method:
byte[] b = new byte[20];
new Random().nextBytes(b);
If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom
.
Java 8 (more secure than previous versions):
byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);
Java 6 & 7:
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);