From 963c58967d97a4c8e65e733c5f046000f2972744 Mon Sep 17 00:00:00 2001 From: binsky Date: Thu, 17 Feb 2022 17:55:17 +0100 Subject: [PATCH] implement generating lowercase passwords with a customizable length --- src/main/java/PasswordGenerator.java | 23 ++++++++++++++++++++++- src/test/java/PasswordGeneratorTest.java | 15 +++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/main/java/PasswordGenerator.java b/src/main/java/PasswordGenerator.java index b36bbbb..1a092a8 100644 --- a/src/main/java/PasswordGenerator.java +++ b/src/main/java/PasswordGenerator.java @@ -1,5 +1,26 @@ +import java.security.SecureRandom; + 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() { - 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(); } } diff --git a/src/test/java/PasswordGeneratorTest.java b/src/test/java/PasswordGeneratorTest.java index 8f3d4b2..8e35b3f 100644 --- a/src/test/java/PasswordGeneratorTest.java +++ b/src/test/java/PasswordGeneratorTest.java @@ -1,6 +1,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import java.util.regex.Pattern; + import static org.junit.jupiter.api.Assertions.*; class PasswordGeneratorTest { @@ -14,6 +16,15 @@ class PasswordGeneratorTest { @Test 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()); } -} \ No newline at end of file +}