Password Generation
In addition to validation, the Passay library enables us to generate passwords. We can provide rules which the generator should use.
To generate a password, we need to have a PasswordGenerator object. Once we have it, we call the generatePassword() method and pass list of CharacterRules. Here is a sample code:
CharacterRule digits = new CharacterRule(EnglishCharacterData.Digit);
PasswordGenerator passwordGenerator = new PasswordGenerator();
String password = passwordGenerator.generatePassword(10, digits);
Assert.assertTrue(password.length() == 10);
Assert.assertTrue(containsOnlyCharactersFromSet(password, "0123456789"));
We should know that we need an object of CharacterData to create CharacterRule. Another interesting fact is that the library provides us with EnglishCharacterData. It is an enum of five sets of characters:
However, nothing can stop us from defining our set of characters. It's as straightforward as implementing the CharacterData interface. Let's see how we can do it:
CharacterRule specialCharacterRule = new CharacterRule(new CharacterData() {
@Override
public String getErrorCode() {
return "SAMPLE_ERROR_CODE";
}
@Override
public String getCharacters() {
return "ABCxyz123!@#";
}
});
PasswordGenerator passwordGenerator = new PasswordGenerator();
String password = passwordGenerator.generatePassword(10, specialCharacterRule);
Assert.assertTrue(containsOnlyCharactersFromSet(password, "ABCxyz123!@#"));
Do'stlaringiz bilan baham: |