Java MD5 Overview

MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value, specified in RFC 1321, MD5 is one in a series of message digest algorithms designed by Professor Ronald Rivest of MIT (Rivest, 1994). MD5 has been employed in a wide variety of security applications, and is also worldwide used to check the integrity of files.

MD5 is a perfect solution for security thinking. The Java developers usually may take over or code MD5 encryption, the MD5 encryption is complicated, for self-coding it’s hard to implement. Java standard edition has MD5 support built in. in package java.security, class MessageDigest supports functionality of a message digest algorithm, such as MD5 or SHA.

1. Example to Hash a String with MD5 algorithm

This is a Java MD5 example, it passes into a string and returns the MD5 encryption value, we used the method getBytes() that converts a plain text to byte array, the digest is then updated from the bytes from the byte array and a hash computation is conducted upon them(using MessageDigest).

MD5.java
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
    public static String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println(getMD5("Javarmi.com"));
    }
}

Java MD5 example Output:

0127f712fc008f857e77a2f3f179c710

2. Another way Hashing String with MD5 algorithm

This is another Java MD5 encryption example, it accepts string and returns MD5 encryption value.

import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
    public static String getMD5(String input) {
        byte[] source;
        try {
            //Get byte according by specified coding.
            source = input.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            source = input.getBytes();
        }
        String result = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source);
            //The result should be one 128 integer
            byte temp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = temp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            result = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println(getMD5("Javarmi.com"));
    }
}

Java MD5 example Output

0127f712fc008f857e77a2f3f179c710

3. File checksum using Java MD5

MD5 algorithm is also widely used for file checksum to ensure that files were not modified by attacker, an example is below that uses Java MD5 hashing algorithm to generate a checksum for file “c:\\apache\\cxf.jar”. you can check whether the printed value matches the original MD5 value which was released by Jar Publisher.

    public static void main(String[] args) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar");

        byte[] dataBytes = new byte[1024];

        int nread = 0;
        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        System.out.println("Digest(in hex format):: " + sb.toString());
    }

Reference

http://download.oracle.com/javase/1.4.2/docs/api/java/security/MessageDigest.html