Use Pasay, which is a password policy enforcement library. Passwords can be generated using configurable rulesets.
pom.xml
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>1.6.0</version>
</dependency>
Password.java
public class Password {
public static String generate() {
List<CharacterRule> rules = Arrays.asList(
new CharacterRule(EnglishCharacterData.UpperCase, 1),
new CharacterRule(EnglishCharacterData.LowerCase, 1),
new CharacterRule(EnglishCharacterData.Digit, 1)
);
PasswordGenerator generator = new PasswordGenerator();
String password = generator.generatePassword(8, rules);
return password;
}
}
PasswordTest.java
public class PasswordTest {
@Test
public void testGenerate() {
String password = Password.generate();
assertTrue(password.length() == 8);
assertTrue(password.matches(".*[a-z].*"));
assertTrue(password.matches(".*[0-9].*"));
assertTrue(password.matches(".*[A-Z].*"));
}
}
Recommended Posts