Generating MD5 Hashes In Java

Web applications frequently need to generate hashes for comparing data, verifying file integrity, generating keys, etc. If your application uses the Apache Commons libraries, you can use the included DigestUtils convenience class to create hashes. If you don’t use the Apache libraries, then you need an alternate way to generate MD5 hashes.

The below code snippet is a simple function that generates a MD5 hash from a given string. It’s simple to use: simply pass the string to be hashed into the function (to_be_md5), and the hash is returned. This function will throw a RuntimeException if an error is encountered (for example, if the passed-in String is null).

 * Calculate a MD5 hash from the provided String. If the 
 * provided String is null, this method will throw a 
 * RuntimeException.
 * @param to_be_md5 A String to calculate a MD5 hash from.
 * @return A MD5 hash calculated from the provided String.
 * @throws RuntimeException If an error was encountered during calculating.
public static String generateMD5(String to_be_md5) {
    String md5_sum = "";
    //If the provided String is null, then throw an Exception.
    if (to_be_md5 == null) {
        throw new RuntimeException("There is no string to calculate a MD5 hash from.");
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(to_be_md5.getBytes("UTF-8"));
        StringBuffer collector = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            collector.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
        md5_sum = collector.toString();
    }//end try
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Could not find a MD5 instance: " + e.getMessage());
    catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Could not translate UTF-8: " + e.getMessage());
    return md5_sum;
}//end generateMD5

Don’t forget to import the following classes: