Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of 20 random bytes?

People also ask

How do you generate a random byte array?

The java. util. Random. nextBytes() method generates random bytes and provides it to the user defined byte array.

How do you generate random bytes in C++?

rand(): rand() function is a predefined method of C++. It is declared in <stdlib. h> header file. rand() is used to generate random number within a range.

What is the byte size of an array?

If we want to determine the size of array, means how many elements present in the array, we have to write calculation with the help of sizeof() operator. Sizeof(arr[]) / sizeof(arr[0]) ; Here, the size of arr[] is 5 and each float takes memory 8 bytes. So, the total memory is consumed = (5 * 8) bytes.

What is a random byte?

random_bytes(int $length ): string. Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.


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 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.


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