Java Password Generator
Usually, we need to generate a secure password for security purposes. There are several ways to generate a strong password in Java. In this section, we will understand how we can generate a strong password having at least two lowercase characters, two uppercase characters, two digits, and two special characters.
There are the following ways to generate a password in Java:
1. Using Passay Library
Passay is one of the most used password policy enforcement libraries. We use the library to generate a password using a configurable ruleset. We can create the necessary rules for passwords by using the default CharacterData implementation. We can also create our custom CharacterData implementation as per our needs.
In order to use Passay library we need to add the following dependency in the POM.xml file:
Let's take an example to understand how we can use the Passay library to generate random passwords:
2. Using RandomStringGenerator
It is another way to generate a secure password, i.e., by using RandomStringGenerator in Apache Commons Text. RandomStringGenerator generates Unicode string having a specified number of code points. We use RandomStringGenerator by creating an instance of the generator by using the Builder class of the RandomStringGenerator.
We can also modify the properties of the generator. There is one drawback of using this method, i.e., we cannot specify the number of characters in each set like Passay. However, we can overcome this drawback by combining the result of multiple sets.
Let's take an example to understand how we can generate a secure password using RandomStringGenerator.
3. Using RandomStringUtils
There is one more way to generate a secure password, i.e., by using RandomStringUtils class in Apache Commons Lang Library. The RandomStringUtils class provides several methods for generating a secure random password. The random() method of the class plays an important role in generating a password.
Let's take an example to understand how we can generate a secure password using RandomStringUtils class.
4. Using Custom Utility Method
There is another last way to generate a secure password, i.e., by using Custom Utility Method. We use the SecureRandom class for creating a custom utility class. Here, we create four methods for getting a character stream of numbers, upper case letters, lower case letters, and special characters of the specified length. After that, we concatenate each one of them to generate a strong password.
Let's take an example to understand how we can generate a secure password using Custom Utility Method:
All the above-discussed methods are useful in generating a random secure password. However, we mostly use Passay and Apache Common Text libraries for generating a random secure password in Java.