In this post under Passay, I will show with example how to generate random password using user defined characters.
To generate a random password, we need to come up with a list of “CharacterRule” instances.
Each “CharacterRule” class take two data as constructor arguments as listed below
1) instance of “CharacterData” interface
2) min number of characters from “CharacterData” to be present
The “CharacterData” interface is used to come up with a list of characters that you want in the password. In other words whitelist of characters.
In our example we want to generate a random password which has alphabetic (upper and lower case) characters and list of special characters (defined by us).
The list of special characters defined by us are
~!@#$%^&*()
Passay out of the box provides “CharacterData” instance for alphabetic (upper and lower case) characters as listed below.
org.passay.EnglishCharacterData.UpperCase
org.passay.EnglishCharacterData.LowerCase
“EnglishCharacterData.UpperCase” is an instance of “CharacterData” which represents all alphabetic characters in uppercase. Similarly “EnglishCharacterData.LowerCase” is an instance of “CharacterData”
which represents all alphabetic characters in lowercase.
To have an instance of “CharacterData” to represents a specific list of special characters we need to come up with custom class implementing “CharacterData” interface as shown below
CustomSpecialCharacterData
class CustomSpecialCharacterData implements CharacterData {
@Override
public String getErrorCode() {
return "INVALID_SPECIAL_CHARACTER";
}
@Override
public String getCharacters() {
return "~!@#$%^&*()";
}
}
In the above code, we created a class “CustomSpecialCharacterData” that implements “CharacterData” interface.
We provide implementations for two abstract methods “getCharacters” and “getErrorCode”.
Below is the main class that shown the usage of “CustomSpecialCharacterData” class.
Main class
1 public class Example21 {
2 public static void main(String[] args) {
3 List<CharacterRule> rules = new ArrayList<>(0);
4 rules.add(new CharacterRule(EnglishCharacterData.UpperCase, 1));
5 rules.add(new CharacterRule(EnglishCharacterData.LowerCase, 1));
6 rules.add(new CharacterRule(new CustomSpecialCharacterData()));
7
8 PasswordGenerator passwordGenerator = new PasswordGenerator();
9
10 String password = passwordGenerator.generatePassword(10, rules);
11
12 System.out.println(password);
13 }
14 }
In the above code, at line 3 I create a list named “rules”.
At line 4, 5, and 6, I add instances of “CharacterRule” one for EnglishCharacterData.UpperCase, another for EnglishCharacterData.LowerCase and the third one for “CustomSpecialCharacterData” class.
At line 8, we create an instance of “PasswordGenerator”.
At line 10, we generate password of min length of 10 characters.
In this way, we generate random password using our own list of characters.