From c8c871c6c202f6766fa10175bf4b227bbcee14e3 Mon Sep 17 00:00:00 2001 From: binsky Date: Sat, 5 Feb 2022 17:35:53 +0100 Subject: [PATCH] implement method to check if a password has been pwned --- src/main/java/HttpApi.java | 7 ++++--- src/main/java/PasswordValidator.java | 24 ++++++++++++++++++++++++ src/test/java/PasswordValidatorTest.java | 5 +++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/main/java/HttpApi.java b/src/main/java/HttpApi.java index 1e3beef..601b696 100644 --- a/src/main/java/HttpApi.java +++ b/src/main/java/HttpApi.java @@ -16,9 +16,10 @@ public class HttpApi { String inputLine; StringBuffer response = new StringBuffer(); - while ((inputLine = in .readLine()) != null) { - response.append(inputLine); - } in .close(); + while ((inputLine = in.readLine()) != null) { + response.append(inputLine + "\n"); + } + in.close(); return response.toString(); } diff --git a/src/main/java/PasswordValidator.java b/src/main/java/PasswordValidator.java index cddd65f..49a60e4 100644 --- a/src/main/java/PasswordValidator.java +++ b/src/main/java/PasswordValidator.java @@ -1,3 +1,6 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -83,4 +86,25 @@ public class PasswordValidator { return null; } + + 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); + 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])) { + return true; + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + return false; + } } diff --git a/src/test/java/PasswordValidatorTest.java b/src/test/java/PasswordValidatorTest.java index 2ffd935..f2c5106 100644 --- a/src/test/java/PasswordValidatorTest.java +++ b/src/test/java/PasswordValidatorTest.java @@ -54,4 +54,9 @@ class PasswordValidatorTest { assertEquals("A233F0E898ED0661D6D47ED0958F16B52E537231".toLowerCase(), PasswordValidator.getSHA1Hash("asdf12")); assertNull(PasswordValidator.getSHA1Hash("")); } + + @Test + void isPwned() { + assertTrue(PasswordValidator.isPwned("asdf12")); + } }