Browse Source

implement method to check if a password has been pwned

feature-password-validator-pwned-password-check
binsky 3 years ago
parent
commit
c8c871c6c2
  1. 5
      src/main/java/HttpApi.java
  2. 24
      src/main/java/PasswordValidator.java
  3. 5
      src/test/java/PasswordValidatorTest.java

5
src/main/java/HttpApi.java

@ -17,8 +17,9 @@ public class HttpApi {
StringBuffer response = new StringBuffer(); StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) { while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
} in .close();
response.append(inputLine + "\n");
}
in.close();
return response.toString(); return response.toString();
} }

24
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.math.BigInteger;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -83,4 +86,25 @@ public class PasswordValidator {
return null; 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;
}
} }

5
src/test/java/PasswordValidatorTest.java

@ -54,4 +54,9 @@ class PasswordValidatorTest {
assertEquals("A233F0E898ED0661D6D47ED0958F16B52E537231".toLowerCase(), PasswordValidator.getSHA1Hash("asdf12")); assertEquals("A233F0E898ED0661D6D47ED0958F16B52E537231".toLowerCase(), PasswordValidator.getSHA1Hash("asdf12"));
assertNull(PasswordValidator.getSHA1Hash("")); assertNull(PasswordValidator.getSHA1Hash(""));
} }
@Test
void isPwned() {
assertTrue(PasswordValidator.isPwned("asdf12"));
}
} }
Loading…
Cancel
Save