From 3ba0dd6158fa3d4e98272a2f52a61ccbe3ad5339 Mon Sep 17 00:00:00 2001 From: binsky Date: Sat, 5 Feb 2022 17:45:18 +0100 Subject: [PATCH] refactor method to check if a password has been pwned --- src/main/java/PasswordValidator.java | 6 ++++-- src/test/java/PasswordValidatorTest.java | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/PasswordValidator.java b/src/main/java/PasswordValidator.java index 49a60e4..c3bf21a 100644 --- a/src/main/java/PasswordValidator.java +++ b/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; } } diff --git a/src/test/java/PasswordValidatorTest.java b/src/test/java/PasswordValidatorTest.java index f2c5106..d0db88a 100644 --- a/src/test/java/PasswordValidatorTest.java +++ b/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("")); } }