Generating random password

In this post under Passay, I will show with example how to generate random password.

For our example I will generate a random password of length 15 characters containing english lowercase characters, uppercase characters, special characters and digits.

Below is the complete code for your reference.

Main class

1  package defaultPackage;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import org.passay.CharacterRule;
7 import org.passay.EnglishCharacterData;
8 import org.passay.PasswordGenerator;
9
10 public class Example5 {
11 public static void main(String[] args) {
12 CharacterRule lowerCaseCharacterRule = new CharacterRule(EnglishCharacterData.LowerCase, 1);
13 CharacterRule upperCaseCharacterRule = new CharacterRule(EnglishCharacterData.UpperCase, 1);
14 CharacterRule digitsCharacterRule = new CharacterRule(EnglishCharacterData.Digit, 1);
15 CharacterRule specialCharacterRule = new CharacterRule(EnglishCharacterData.Special, 1);
16
17 List<CharacterRule> rules = new ArrayList<>(0);
18 rules.add(lowerCaseCharacterRule);
19 rules.add(upperCaseCharacterRule);
20 rules.add(digitsCharacterRule);
21 rules.add(specialCharacterRule);
22
23 PasswordGenerator passwordGenerator = new PasswordGenerator();
24 String output = passwordGenerator.generatePassword(15, rules);
25 System.out.println(output);
26 }
27 }

In the above code, from line 12 to 15, I create rules.

Each rule is an instance of “CharacterRule” class.

The rules are
1) the password should have atleast one lowercase english character. Refer to line 12
2) the password should have atleast one uppercase english character. Refer to line 13
3) the password should have atleast one digit. Refer to line 14
4) the password should have atleast one special character. Refer to line 15.

From line 17 to 21, I create a list and add the rules to the list

At line 23, I create an instance of “PasswordGenerator” class

At line 24, I call non-static method “generatePassword” of “PasswordGenerator” class, passing two arguments.
1) first argument being the length of the password
2) second argument being the list of rules.

The output of “generatePassword” method is stored in String variable “output” and printed to console.

In this way, we can use Passay to generate random passwords.

Leave a comment