How to calculate a MD5 checksum with Java

Sometimes you need an easy way to recognise the correctness of a download. Below is a snippet how to use the MD5 message-digest algorithm with Java:

import static java.nio.charset.StandardCharsets.UTF_8;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public static void main(String[] args) {
  byte[] payload = "payload".getBytes(UTF_8);.

  MessageDigest messageDigest = MessageDigest.getInstance("MD5");
  String md5 = new BigInteger(1, messageDigest.digest(payload)).toString(16);
  ...
}

If you don't want to remember all the API details you might want to look at Commons Codec's DigestUtils:

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

public static void main(String[] args) {
  byte[] payload = "payload".getBytes(UTF_8);.

  DigestUtils.md5Hex(payload);.
  ...
}