How to Generate MD5 Hash in Java

A key concept in cryptography is the concept of hash values. A hash is a unique value corresponding to a given data with the following properties,

  • It is impossible to arrive at the original message from hash.
  • Two different messages practically cannot have the same hash.
  • Modifying message changes the corresponding hash.
  • It is easy to generate the hash value with the above properties.

There are a number of well known algorithms for generating hash values. Two of the most popular ones are SHA and MD5. The following example Java program creates an MD5 hash for a given string. This program uses the java.security.MessageDigest class for creating the MD5 hash. MessageDigest is also capable of generating hash values using SHA-1 and SHA-256 algorithms.

Note that we are using DataTypeConverter to convert the arbitrary hash binary value in readable hexadecimal format. This enables us to share the hash over email or printed material. This conversion is not required if you don't want a readable version of MD5 hash.

import java.security.MessageDigest;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;

/**
 * Demonstrates how to generate MD5 hash using Java
 * @author JJ
 */
public class MD5HashGenerator {

    public static void main(String[] args) {
        Scanner sn = new Scanner(System.in);
        System.out.print("Please enter data for which MD5 is required:");
        String data = sn.nextLine();
        
        MD5HashGenerator sj = new MD5HashGenerator();
        String hash = sj.getMD5Hash(data);
        System.out.println("The MD5 (hexadecimal encoded) hash is:"+hash);
    }

    /**
     * Returns a hexadecimal encoded MD5 hash for the input String.
     * @param data
     * @return 
     */
    private String getMD5Hash(String data) {
        String result = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hash = digest.digest(data.getBytes("UTF-8"));
            return bytesToHex(hash); // make it printable
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
    
    /**
     * Use javax.xml.bind.DatatypeConverter class in JDK to convert byte array
     * to a hexadecimal string. Note that this generates hexadecimal in upper case.
     * @param hash
     * @return 
     */
    private String  bytesToHex(byte[] hash) {
        return DatatypeConverter.printHexBinary(hash);
    }
}