Browse Source

implement sha1 hash generation

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

29
src/main/java/PasswordValidator.java

@ -1,3 +1,6 @@
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class PasswordValidator { public class PasswordValidator {
@ -54,4 +57,30 @@ public class PasswordValidator {
public void setRequireDigit(boolean requireDigit) { public void setRequireDigit(boolean requireDigit) {
this.requireDigit = requireDigit; this.requireDigit = requireDigit;
} }
public static String getSHA1Hash(String input) {
if (input.length() > 0) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
StringBuilder hashtext = new StringBuilder();
hashtext.append(no.toString(16));
// Add preceding 0s to make it 32 bit
while (hashtext.length() < 32) {
hashtext.insert(0, "0");
}
return hashtext.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return null;
}
} }

7
src/test/java/PasswordValidatorTest.java

@ -47,4 +47,11 @@ class PasswordValidatorTest {
assertFalse(passwordValidator.validate("ABCDEF8")); assertFalse(passwordValidator.validate("ABCDEF8"));
assertTrue(passwordValidator.validate("abCDE8F")); assertTrue(passwordValidator.validate("abCDE8F"));
} }
@Test
void getSHA1Hash() {
assertEquals("356A192B7913B04C54574D18C28D46E6395428AB".toLowerCase(), PasswordValidator.getSHA1Hash("1"));
assertEquals("A233F0E898ED0661D6D47ED0958F16B52E537231".toLowerCase(), PasswordValidator.getSHA1Hash("asdf12"));
assertNull(PasswordValidator.getSHA1Hash(""));
}
} }
Loading…
Cancel
Save