This post will discuss how to generate a cryptographically strong random alphanumeric password of the desired length in Java.

1. Using SecureRandom.nextInt(…) with StringBuilder

A simple solution is to randomly choose characters from the defined ASCII range and construct a string of the desired length out of it. To construct a random alphanumeric password, the ASCII range should consist of digits, uppercase, and lowercase characters.

Following is a simple Java program to demonstrate the idea. SecureRandom class is used over the Random class to ensure a cryptographically strong random number generator.

Download  Run Code

 
Here’s an equivalent version using the Stream API.

Download  Run Code

2. Using SecureRandom.ints(…) + Stream

In Java 8 and above, the SecureRandom.ints(…) method can be used to effectively return a stream of pseudorandom values within the specified range. To restrict the generated pseudorandom values to alphanumeric values, use the filter(…) Stream method. To restrict the filtered alphanumeric pseudorandom values to the desired length, call the limit(…) method. Finally, collect the values in the resultant stream and construct a String.

Download  Run Code

 
The above solution generates a strong random alphanumeric password of the desired length. We can further simplify the code to generate only numeric (0-9) password, password with all uppercase (A-Z) characters or all lowercase (a-z) characters or any other characters that fall within some ASCII range.

For example, to generate a password with all lower case letters set the range as 97-122 (ASCII value of 'a'-'z').

Download  Run Code

3. Using Apache Commons Text

Several third-party libraries provide utility methods for working with random values. If you prefer the Apache Commons Text library, the RandomStringGenerator class can generate random Unicode strings. Its instances are created using a builder class.

⮚ Using withinRange(…) with filteredBy(…):

Download Code

 
RandomStringGenerator instances use the default random number generator (RNG). We can use a custom RNG by calling the Builder.usingRandom(…) method, as shown below:

⮚ Using selectFrom(…):

Download Code

4. Using Apache Commons Lang

We can also use the RandomStringUtils class by Apache Commons Lang library. It offers several methods like randomAlphabetic, randomAlphanumeric, randomNumeric, etc., to create a random string.

For instance, using randomAlphanumeric(…) will create a random alphanumeric string of the specified length.

Download Code

 
To explicitly construct a random string from specified characters, call the random(…) method.

Download Code

That’s all about generating a random password in Java.