From 1d591771f4b709178e062080237531704c6d4655 Mon Sep 17 00:00:00 2001 From: binsky Date: Sat, 5 Feb 2022 17:12:55 +0100 Subject: [PATCH] implement sha1 hash generation --- src/main/java/PasswordValidator.java | 29 ++++++++++++++++++++++++ src/test/java/PasswordValidatorTest.java | 7 ++++++ 2 files changed, 36 insertions(+) diff --git a/src/main/java/PasswordValidator.java b/src/main/java/PasswordValidator.java index 9cb4f03..cddd65f 100644 --- a/src/main/java/PasswordValidator.java +++ b/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; public class PasswordValidator { @@ -54,4 +57,30 @@ public class PasswordValidator { public void setRequireDigit(boolean 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; + } } diff --git a/src/test/java/PasswordValidatorTest.java b/src/test/java/PasswordValidatorTest.java index 78d9335..2ffd935 100644 --- a/src/test/java/PasswordValidatorTest.java +++ b/src/test/java/PasswordValidatorTest.java @@ -47,4 +47,11 @@ class PasswordValidatorTest { assertFalse(passwordValidator.validate("ABCDEF8")); assertTrue(passwordValidator.validate("abCDE8F")); } + + @Test + void getSHA1Hash() { + assertEquals("356A192B7913B04C54574D18C28D46E6395428AB".toLowerCase(), PasswordValidator.getSHA1Hash("1")); + assertEquals("A233F0E898ED0661D6D47ED0958F16B52E537231".toLowerCase(), PasswordValidator.getSHA1Hash("asdf12")); + assertNull(PasswordValidator.getSHA1Hash("")); + } }