This is a small variation of Andranik and Den Delimarsky's answers above, but its a bit more concise and does not require any bitwise logic. Instead, it uses the built-in String.format method to convert bytes to two characters in hexadecimal strings (does not separate 0). Usually I just comment on their answers, but I don't have a reputation to do this.
public static String md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); StringBuilder hexString = new StringBuilder(); for (byte digestByte : md.digest(input.getBytes())) hexString.append(String.format("%02X", digestByte)); return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
If you want to return a string string instead, just change %02X to %02X .
Edit: Using BigInteger as with wzbozon's answer, you can make the answer even more concise:
public static String md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); BigInteger md5Data = new BigInteger(1, md.digest(input.getBytes())); return String.Format("%032X", md5Data); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
rsimp Sep 09 '16 at 22:30 2016-09-09 22:30
source share