Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a secure random alphanumeric string in Java efficiently?

How do you generate a secure random (or pseudo-random) alphanumeric string in Java efficiently?

like image 351
devon Avatar asked Aug 18 '11 17:08

devon


People also ask

How do you generate a secure random alphanumeric string in java?

SecureRandom randomGenerator = new SecureRandom(); byte[] randomBytes = new byte[20]; randomGenerator. nextBytes(randomBytes); String randomString = new BigInteger(1, randomBytes). toString(16); It you want to a little more efficient variant, specify randomGenerator as class field or as a static field.

How do you generate a secure random string?

Generating a Secure Random String$random = random_bytes(10); The function returns a random string, suitable for cryptographic use, of the number bytes passed as an argument (10 in the above example). The random_bytes() function returns a binary string which may contain the \0 character.

How do you generate random unique strings in java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


1 Answers

Initialize an array containing all the accepted chars (CHARS_ARRAY), then instantiate a SecureRandom instance, and call nextInt(CHARS_ARRAY.length) repeatedly to get a random index in your char array. Append each char to a StringBuilder until you get the expected number of chars.

like image 68
JB Nizet Avatar answered Sep 21 '22 13:09

JB Nizet