How to create an array of 20 random bytes?
How can I create an array of 20 random b开发者_运维百科ytes in Java?
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);
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.
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);
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]);
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.
精彩评论