Generate a random password in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.security.SecureRandom; class Main { // Method to generate a random alphanumeric password of a specific length public static String generateRandomPassword(int len) { // ASCII range – alphanumeric (0-9, a-z, A-Z) final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; SecureRandom random = new SecureRandom(); StringBuilder sb = new StringBuilder(); // each iteration of the loop randomly chooses a character from the given // ASCII range and appends it to the `StringBuilder` instance for (int i = 0; i < len; i++) { int randomIndex = random.nextInt(chars.length()); sb.append(chars.charAt(randomIndex)); } return sb.toString(); } public static void main(String[] args) { int len = 10; System.out.println(generateRandomPassword(len)); } } |
Here’s an equivalent version using the Stream API.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.security.SecureRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { // Method to generate a random alphanumeric password of a specific length public static String generateRandomPassword(int len) { // ASCII range – alphanumeric (0-9, a-z, A-Z) final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; SecureRandom random = new SecureRandom(); // each iteration of the loop randomly chooses a character from the given // ASCII range and appends it to the `StringBuilder` instance return IntStream.range(0, len) .map(i -> random.nextInt(chars.length())) .mapToObj(randomIndex -> String.valueOf(chars.charAt(randomIndex))) .collect(Collectors.joining()); } public static void main(String[] args) { int len = 10; System.out.println(generateRandomPassword(len)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.security.SecureRandom; class Main { // Method to generate a random alphanumeric password of a specific length public static String generateRandomPassword(int len, int randNumOrigin, int randNumBound) { SecureRandom random = new SecureRandom(); return random.ints(randNumOrigin, randNumBound + 1) .filter(i -> Character.isAlphabetic(i) || Character.isDigit(i)) .limit(len) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } public static void main(String[] args) { int len = 10; int randNumOrigin = 48, randNumBound = 122; System.out.println(generateRandomPassword(len, randNumOrigin, randNumBound)); } } |
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').
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.security.SecureRandom; import java.util.stream.Collectors; class Main { // Method to generate a random alphanumeric password of a specific length public static String generateRandomPassword(int len, int randNumOrigin, int randNumBound) { SecureRandom random = new SecureRandom(); return random.ints(len, randNumOrigin, randNumBound + 1) .mapToObj(i -> String.valueOf((char)i)) .collect(Collectors.joining()); } public static void main(String[] args) { int len = 10; int randNumOrigin = 97, randNumBound = 122; System.out.println(generateRandomPassword(len, randNumOrigin, randNumBound)); } } |
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(…):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import org.apache.commons.text.CharacterPredicates; import org.apache.commons.text.RandomStringGenerator; class Main { // Method to generate a random alphanumeric password of a specific length public static String generateRandomPassword(int len, int randNumOrigin, int randNumBound) { RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange(randNumOrigin, randNumBound) .filteredBy(CharacterPredicates.ASCII_ALPHA_NUMERALS) .build(); return generator.generate(len); } public static void main(String[] args) { int len = 10; int randNumOrigin = '0', randNumBound = 'z'; System.out.println(generateRandomPassword(len, randNumOrigin, randNumBound)); } } |
RandomStringGenerator instances use the default random number generator (RNG). We can use a custom RNG by calling the Builder.usingRandom(…) method, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static String generateRandomPassword(int len, int randNumOrigin, int randNumBound) { // Using Apache Commons RNG for randomness SecureRandom rng = new SecureRandom(); RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange(randNumOrigin, randNumBound) .filteredBy(CharacterPredicates.ASCII_ALPHA_NUMERALS) .usingRandom(rng::nextInt) .build(); return generator.generate(len); } |
⮚ Using selectFrom(…):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import org.apache.commons.text.RandomStringGenerator; class Main { // Method to generate a random alphanumeric password of a specific length // using Apache Commons Text `RandomStringGenerator` public static String generateRandomPassword(int len) { // provide alphanumeric ASCII range (0-9, a-z, A-Z) final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; RandomStringGenerator randomStringGenerator = new RandomStringGenerator.Builder() .selectFrom(chars.toCharArray()) .build(); return randomStringGenerator.generate(len); } public static void main(String[] args) { int len = 10; System.out.println(generateRandomPassword(len)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import org.apache.commons.lang3.RandomStringUtils; class Main { // Method to generate a random alphanumeric password of a specific length // using Apache Commons Lang `RandomStringUtils` public static String generateRandomPassword(int len) { return RandomStringUtils.randomAlphanumeric(len); } public static void main(String[] args) { int len = 10; System.out.println(generateRandomPassword(len)); } } |
To explicitly construct a random string from specified characters, call the random(…) method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import org.apache.commons.lang3.RandomStringUtils; class Main { // Method to generate a random alphanumeric password of a specific length // using Apache Commons Lang `RandomStringUtils` public static String generateRandomPassword(int len) { final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; return RandomStringUtils.random(len, chars); } public static void main(String[] args) { int len = 10; System.out.println(generateRandomPassword(len)); } } |
That’s all about generating a random password in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)