Here is some code that you can use to hash passwords or other secrets in Java. I usually prefer to have such methods in a separate utility class:
protected static MessageDigest getDigest() throws NoSuchAlgorithmException { if (digest == null) { digest = MessageDigest.getInstance(&qout;MD5&qout;); } return digest; } public static byte[] digestString(String s) { if (s == null) return null; try { MessageDigest digest = getDigest(); digest.update(s.getBytes()); return digest.digest(); } catch (Exception e) { log.error(&qout;Digesting problem:&qout;, e); } return null; } public static String encodePassword(String s) { byte b[] = digestString(s); if (b == null) return null; String rc = new String(Base64.encodeBase64(b)); if (rc.length() > 50) rc = rc.substring(0, 50); return rc; } |
Use the function encodePassword() to hash your string. Please note that the hash value is limited to a length of 50 characters.