Browse Source

implement generating lowercase passwords with a customizable length

feature-password-generator
binsky 3 years ago
parent
commit
963c58967d
  1. 23
      src/main/java/PasswordGenerator.java
  2. 13
      src/test/java/PasswordGeneratorTest.java

23
src/main/java/PasswordGenerator.java

@ -1,5 +1,26 @@
import java.security.SecureRandom;
public class PasswordGenerator { public class PasswordGenerator {
final String lowercaseCharacters = "abcdefghjkmnpqrstuvwxyz";
int length = 12;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String generateRandomPassword() { public String generateRandomPassword() {
return "";
StringBuilder generatedPassword = new StringBuilder();
SecureRandom rand = new SecureRandom();
for (int generatorPosition = 0; generatorPosition < getLength(); generatorPosition++) {
generatedPassword.append(lowercaseCharacters.charAt(rand.nextInt(lowercaseCharacters.length())));
}
return generatedPassword.toString();
} }
} }

13
src/test/java/PasswordGeneratorTest.java

@ -1,6 +1,8 @@
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class PasswordGeneratorTest { class PasswordGeneratorTest {
@ -14,6 +16,15 @@ class PasswordGeneratorTest {
@Test @Test
void generateRandomPassword() { void generateRandomPassword() {
assertSame("", passwordGenerator.generateRandomPassword());
assertNotSame("", passwordGenerator.generateRandomPassword());
assertEquals(passwordGenerator.generateRandomPassword().length(), passwordGenerator.getLength());
// test length requirement
passwordGenerator.setLength(33);
assertEquals(passwordGenerator.getLength(), 33);
assertEquals(passwordGenerator.generateRandomPassword().length(), passwordGenerator.getLength());
// test lowercase requirement
assertTrue(Pattern.compile("^(?=.*[a-z]).+$").matcher(passwordGenerator.generateRandomPassword()).matches());
} }
} }
Loading…
Cancel
Save