Browse Source

implement generating passwords with special characters

feature-password-generator
binsky 3 years ago
parent
commit
4c458fb710
  1. 13
      src/main/java/PasswordGenerator.java
  2. 8
      src/test/java/PasswordGeneratorTest.java

13
src/main/java/PasswordGenerator.java

@ -5,11 +5,13 @@ public class PasswordGenerator {
final String lowercaseCharacters = "abcdefghjkmnpqrstuvwxyz";
final String uppercaseCharacters = "ABCDEFGHJKMNPQRSTUVWXYZ";
final String digits = "0123456789";
final String specialCharacters = ".!?=@#$()%^&/*_-+";
private int length = 12;
private boolean useUppercase = true;
private boolean useLowercase = true;
private boolean useDigits = true;
private boolean useSpecialCharacters = true;
public String generateRandomPassword() {
@ -26,6 +28,9 @@ public class PasswordGenerator {
if (isUseDigits()) {
characterPool += digits;
}
if (isUseSpecialCharacters()) {
characterPool += specialCharacters;
}
for (int generatorPosition = 0; generatorPosition < getLength(); generatorPosition++) {
generatedPassword.append(characterPool.charAt(rand.nextInt(characterPool.length())));
@ -57,6 +62,14 @@ public class PasswordGenerator {
this.useDigits = useDigits;
}
public boolean isUseSpecialCharacters() {
return useSpecialCharacters;
}
public void setUseSpecialCharacters(boolean useSpecialCharacters) {
this.useSpecialCharacters = useSpecialCharacters;
}
public int getLength() {
return length;
}

8
src/test/java/PasswordGeneratorTest.java

@ -47,4 +47,12 @@ class PasswordGeneratorTest {
passwordGenerator.setUseDigits(true);
assertTrue(Pattern.compile("^(?=.*\\d).+$").matcher(passwordGenerator.generateRandomPassword()).matches());
}
@Test
void testPasswordSpecialCharactersRequirement() {
passwordGenerator.setUseSpecialCharacters(false);
assertFalse(Pattern.compile("^(?=.*[.!?=@#$()%^&/*_\\-+]).+$").matcher(passwordGenerator.generateRandomPassword()).matches());
passwordGenerator.setUseSpecialCharacters(true);
assertTrue(Pattern.compile("^(?=.*[.!?=@#$()%^&/*_\\-+]).+$").matcher(passwordGenerator.generateRandomPassword()).matches());
}
}
Loading…
Cancel
Save