Browse Source

refactor method to check if a password has been pwned

feature-password-validator-pwned-password-check
binsky 3 years ago
parent
commit
3ba0dd6158
  1. 6
      src/main/java/PasswordValidator.java
  2. 2
      src/test/java/PasswordValidatorTest.java

6
src/main/java/PasswordValidator.java

@ -15,6 +15,7 @@ public class PasswordValidator {
private final Pattern uppercasePattern = Pattern.compile("^(?=.*[A-Z]).+$");
private final Pattern lowercasePattern = Pattern.compile("^(?=.*[a-z]).+$");
private final Pattern digitPattern = Pattern.compile("^(?=.*\\d).+$");
private static final String pwnedPasswordsApiUrl = "https://api.pwnedpasswords.com/range/";
public boolean validate(String password) {
if (password.length() < minLength) {
@ -90,13 +91,14 @@ public class PasswordValidator {
public static boolean isPwned(String password) {
String sha1 = PasswordValidator.getSHA1Hash(password);
if (sha1 != null) {
String url = "https://api.pwnedpasswords.com/range/" + sha1.substring(0, 5);
String url = pwnedPasswordsApiUrl + sha1.substring(0, 5);
try {
String result = HttpApi.sendHttpGETRequest(url);
BufferedReader bufReader = new BufferedReader(new StringReader(result));
String line = null;
while ((line = bufReader.readLine()) != null) {
if (sha1.toUpperCase().endsWith(line.split(":")[0])) {
String[] lineSplit = line.split(":");
if (lineSplit.length > 0 && sha1.toUpperCase().endsWith(lineSplit[0])) {
return true;
}
}

2
src/test/java/PasswordValidatorTest.java

@ -58,5 +58,7 @@ class PasswordValidatorTest {
@Test
void isPwned() {
assertTrue(PasswordValidator.isPwned("asdf12"));
assertFalse(PasswordValidator.isPwned("=phan0johB4aisae6Mie0jeip9Saejahc0iuvuth7ahv9uoni6o*_.+"));
assertFalse(PasswordValidator.isPwned(""));
}
}
Loading…
Cancel
Save