Java MD5 Hashing Example

MD5 is one in a series of message digest algorithms designed by Professor Ronald Rivest of MIT (Rivest, 1994). When analytic work indicated that MD5’s predecessor MD4 was likely to be insecure, MD5 was designed in 1991 to be a secure replacement. (Weaknesses were indeed later found in MD4 by Hans Dobbertin.)

MD5 is a widely used hashing algorithm in many companies and industries, here are two examples for the MD5 implementation.

1. File checksum with MD5

It will use MD5 hashing algorithm to generate a checksum for file “c:\\loging.log”.

package com.mkyong.test;
 
import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class MD5CheckSumExample 
{
    public static void main(String[] args)throws Exception
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream fis = new FileInputStream("c:\\loging.log");
 
        byte[] dataBytes = new byte[1024];
 
        int nread = 0; 
        while ((nread = fis.read(dataBytes)) != -1) {
          md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();
 
        //convert the byte to hex format method 1
        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());
 
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<mdbytes.length;i++) {
    		String hex=Integer.toHexString(0xff & mdbytes[i]);
   	     	if(hex.length()==1) hexString.append('0');
   	     	hexString.append(hex);
    	}
    	System.out.println("Digest(in hex format):: " + hexString.toString());
    }
}
Output
Digest(in hex format):: e72c504dc16c8fcd2fe8c74bb492affa
Digest(in hex format):: e72c504dc16c8fcd2fe8c74bb492affa

2. Hashing String with MD5

It will use MD5 hashing algorithm to generate a hash value for a password “123456”.

package com.mkyong.test;
 
import java.security.MessageDigest;
 
public class MD5HashingExample 
{
    public static void main(String[] args)throws Exception
    {
    	String password = "123456";
 
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Digest(in hex format):: " + sb.toString());
 
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<byteData.length;i++) {
    		String hex=Integer.toHexString(0xff & byteData[i]);
   	     	if(hex.length()==1) hexString.append('0');
   	     	hexString.append(hex);
    	}
    	System.out.println("Digest(in hex format):: " + hexString.toString());
    }
}
Output
Digest(in hex format):: e10adc3949ba59abbe56e057f20f883e
Digest(in hex format):: e10adc3949ba59abbe56e057f20f883e

Reference

1. http://en.wikipedia.org/wiki/MD5
2. http://forums.sun.com/thread.jspa?threadID=5169003

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • http://itsvenkis.blogspot.in itsvenkis

    Hi!!! I really unable to understand why you had

    Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)

    instead of

    Integer.toString((byteData[i] & 0xff), 16)

    If it is just for padding zeros you could have checked the length and added a zero. May be I am missing the whole point. Can you pelase help me understand?

  • elton

    hello sir,
    i want a simple java code to calculate md5 of any input i give from a keyboard

  • Pingback: Melakukan hashing MD5 pada Java | Super|User|Corner()

  • gli00001

    new BigInteger(1, md.digest()).toString(16) should save the loop using stringBuffer

  • siri

    I have 100 file (which are not stored on my computer)that are located on a server and I have path to each one of them, I need a code to calculate the MD5 of each one of the and store it in an excel sheet individually.

  • Wilson

    Is there any way convert the digested “e10adc3949ba59abbe56e057f20f883e” key to original password “123456”. If you know please let us know.

    Thanks
    Wilson.

    • Facepalm

      Idiot.

  • natesan

    Dear Sir,
    in this example (ff) variable showing some errors.how to rectify the error. thank you sir.the error was ff cannot be resolved to a variable.

  • http://bouchtaoui.plogspot.com nordin

    md5 is useful when hashing filenames for some reason. I’ll use this snippet of code to hash imagefile names, it’s temporary for a few weeks and than I’ll remove them. The advantage is that this hash method is less cpu intensive and the chances to have the same hash values are very very small. Furthermore, this is a nice simple example, so using a sha-1 instead of md5 is almost the same. Thank you for your snippet :-)

  • Pingback: Java MD5 Hashing Example | Devin Patel()

  • Pingback: Hashing String with MD5 « tediscript.wordpress.com()

  • Cristian

    Hello, I am wondering why you would use MD5, an algorithm thats has already been broken instead of something like GrandCentral which creates a password digest based on the time of day using SHA-512. GrandCentral also includes the SimpleCrypto class which can generate hashes and checksums using MD5, SHA1, SHA-256, SHA-384 and SHA-512. Just a suggestion. http://code.google.com/p/grandcentral/

    • http://www.mkyong.com mkyong

      MD5 is not broken, it has chance (really small percentage to generate same hash), SHA is always recommended. But, due to the popularity of MD5, many are still using it. This is an example to show you how to use MD5 in Java, again SHA is always recommended. And thanks for your suggested GrandCentral library, it look promising :)

      • Cristian Rivera

        Yes, I’m sorry for my poor use of words. I meant that yes it is widely uses do to it’s popularity but there is still a better chance of cracking an MD5 hash rather than an SHA hash. Also thank you for your comment about GrandCentral I am developing it to provide developers with and easy to use tool that they can rely on to perform certain tasks easily. I will be updating later this weekend to v1.2 if you are interested.

  • Pingback: A short and clean way of computing MD5 in Java | The refuge()

  • http://www.sspmcoe.com santosh

    sir,
    give me suggestion for password hashing using md 5 algorithm in java.

  • Rocky Madden

    Been moving towards always using SHA hashing myself, especially with recent CPU processor support/improvements being added each generation. Trusty old MD5 doesn’t let down most of the time though.

    • http://www.mkyong.com mkyong

      ya, SHA is recommended because MD5 will causing the collision issue (same checksum for different files).