Programming Tips - Java: Make a MD5 hash (digest)

Date: 2022sep22 Update: 2025oct2 Language: Java Q. Java: Make a MD5 hash (digest) A. Warning: MD5 isn't cryptographically secure any more. But it still has uses. Full example:
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; class Demo { public static String toHexString(final byte[] ba) { final StringBuilder sb = new StringBuilder(); for(int i = 0; i < ba.length; i++) { sb.append(String.format("%02x", ba[i])); } return sb.toString(); } public static String makeMD5(final String thingOne, final String thingTwo) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { // Every implementation of the Java platform is required to support // the following standard MessageDigest algorithms: MD5 SHA-1 SHA-256 return ""; } md.update(thingOne.getBytes()); md.update(thingTwo.getBytes()); final byte byteData[] = md.digest(); return toHexString(byteData); } public static final void main(String []args) { String md5 = makeMD5("hello", "world"); System.out.println("md5=" + md5); } }
Output:
md5=fc5e038d38a57032085441e7fe7010b0