public String encodePassword(String password, Object salt) { try { return "{CRYPT}" + md5Crypt.crypt(password); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No MD5 Algorithm", e); } }
public boolean isPasswordValid(String encPassword, String inputPassword, Object salt) { try { String encryptedPassword = encPassword; if (encryptedPassword.startsWith("{crypt}") || encryptedPassword.startsWith("{CRYPT}")) { encryptedPassword = encryptedPassword.substring("{crypt}".length()); } int lastDollar = encryptedPassword.lastIndexOf('$'); String realSalt = encryptedPassword.substring("$1$".length(), lastDollar); String check = md5Crypt.crypt(inputPassword, realSalt); return check.equals(encryptedPassword); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No MD5 Algorithm", e); } }
@Test public void testEncryptAndVerify() throws Exception { PasswordEncoder encoder = lookup(PasswordEncoder.class, "crypt"); String crypted = encoder.encodePassword("test", null); // System.out.println( "Crypted password: \'" + crypted + "\'" ); int lastIdx = crypted.lastIndexOf('$'); int firstIdx = crypted.indexOf('$'); String salt = crypted.substring(firstIdx + "$1$".length(), lastIdx); String check = "{CRYPT}" + MD5Crypt.unixMD5("test", salt); // System.out.println( "Check value: \'" + check + "\'" ); Assert.assertEquals(check, crypted); Assert.assertTrue(encoder.isPasswordValid(crypted, "test", null)); }