Java MD5 Hashing Example

In this article, we will show you how to use a MD5 algorithm to hash a String and generate a checksum for a file.

1. MessageDigest

1.1 MD5 to Hash a string.

PasswordMD5.java

package com.mkyong.hashing;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordMD5 {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        String password = "123456";

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashInBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));

        StringBuilder sb = new StringBuilder();
        for (byte b : hashInBytes) {
            sb.append(String.format("%02x", b));
        }
        System.out.println(sb.toString());

    }

}

Output


e10adc3949ba59abbe56e057f20f883e

1.2 File checksum.

d:\server.log

123456
FileCheckSum.java

package com.mkyong.hashing;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileCheckSum {

    public static void main(String[] args) throws NoSuchAlgorithmException, IOException {

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashInBytes = checksum("d:\\server.log", md);
        System.out.println(bytesToHex(hashInBytes));

    }

    private static byte[] checksum(String filepath, MessageDigest md) throws IOException {

        try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
            while (dis.read() != -1) ; //empty loop to clear the data
            md = dis.getMessageDigest();
        }

        return md.digest();

    }

    private static String bytesToHex(byte[] hashInBytes) {

        StringBuilder sb = new StringBuilder();
        for (byte b : hashInBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();

    }

}

Output


e10adc3949ba59abbe56e057f20f883e

2. Apache Commons Codec

Alternatively, try this Apache Commons Codecs library for hashing.

pom.xml

	<dependency>
		<groupId>commons-codec</groupId>
		<artifactId>commons-codec</artifactId>
		<version>1.11</version>
    </dependency>

2.1 Hash a String.

PasswordMD5.java

package com.mkyong.hashing;

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

public class PasswordMD5 {

    public static void main(String[] args) {

        String password = "123456";

        String result = DigestUtils.md5Hex(password);
        System.out.println(result);

    }

}

Output


e10adc3949ba59abbe56e057f20f883e

2.2 File checksum.

FileCheckSum.java

package com.mkyong.hashing;

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

import java.io.FileInputStream;
import java.io.IOException;

public class FileCheckSum {

    public static void main(String[] args) throws IOException {

        String result = DigestUtils.md5Hex(new FileInputStream("d:\\server.log"));
        System.out.println(result);

    }

}

Output


e10adc3949ba59abbe56e057f20f883e

References

  1. Apache Commons Codec
  2. Java – How to convert Bytes to Hex
  3. Wikipedia – MD5
  4. MessageDigest JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
24 Comment threads
8 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
26 Comment authors
julioVladimirTewariguestCafebabe2018 Recent comment authors
newest oldest most voted
Vladimir
Guest
Vladimir

My friend, thank you very much from Russia !!!!

Cafebabe2018
Guest
Cafebabe2018

for (int i = 0; i < byteData.length; i++) {
sb.append(String.format("%02x", byteData[i]));
}

Qazi Jalil
Guest
Qazi Jalil

but if i do it over some file it works correctly but if i change its path or location of file its hash changes why me not able to fix this error

Eugen Maysyuk
Guest
Eugen Maysyuk

You forgot to close FileInputStream.

Nishu
Guest
Nishu

Its giving a different hash every time with the same input file which should not be the case with MD5 algorithm. I think there is some problem in this code

Napster85
Guest
Napster85

What about if you use this:

sb.append(String.format(“%02X”, buffer[i]));

;)

julio
Guest
julio

alguien me dice como desencriptar esta clave E67480325049070253

Prashant
Guest
Prashant

What is the point to generate md5 hash of a password if that cant be reversed?

guest
Guest
guest

You save the generated md5 hash in a file or any other method, If someone fojnd it, s/he wont be able to get the original password (except by brute force) … anyway, when you or anyone else enter the password, you hash the entered password and compare it to the md5 you generated previously.

so in breif, instead of comparing the explict passwords to check if they match, you check theirs hashs.

Ahmed ElZayady
Guest
Ahmed ElZayady

Hi .. The string method above isn’t working fine if the string contains a £ sign, don’t know why. On other hand, the function provided in this link http://www.asjava.com/core-java/java-md5-example/ did work fine with £. May be it is something you might be interested to look into.

Murali Mohan
Guest
Murali Mohan

The world is a fast-changing place. Check out Apache Shiro’s cryptography capabilities.

https://www.youtube.com/watch?v=5ZepGFzYHpE

itsvenkis
Guest
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?

none
Guest
none

Yes, it’s for padding, and It’s just easier syntax than introducing conditional branching.

elton
Guest
elton

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

trackback
Melakukan hashing MD5 pada Java | Super|User|Corner

[…] MKYong […]

siri
Guest
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
Guest
Wilson

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

Thanks
Wilson.

Facepalm
Guest
Facepalm

Idiot.

Saifur Rahman Mohsin
Guest
Saifur Rahman Mohsin

You can do this by generating a rainbow table and then comparing the hash with original text. However longer texts will not give the correct output for obvious reasons..!

Tewari
Guest
Tewari

MD5 is one way digest algorithm, this means that you are not supposed/allowed to convert the hash back to text. I would not suggest you to go with Rainbow tables since you would then have to secure and manage the rainbow table itself, besides the bigger the table gets the higher the seek time gets and is therefore not effective. If you want to encrypt text so that it can be converted back to original text you can try base64encoding with secret key.

natesan
Guest
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.

nordin
Guest
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 :-)

trackback
Java MD5 Hashing Example | Devin Patel

[…] Java MD5 Hashing Example. […]

trackback
Hashing String with MD5 « tediscript.wordpress.com

[…] String with MD5http://www.mkyong.com/java/java-md5-hashing-example/ Share this:TwitterFacebookLike this:LikeBe the first to like this. […]

Cristian
Guest
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/

trackback
A short and clean way of computing MD5 in Java | The refuge

[…] are multiple articles (01, 02, 03, 04) talking about how to compute MD5 in Java and some of them have some gotchas regarding the length […]

santosh
Guest
santosh

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

Rocky Madden
Guest
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.

gli00001
Guest
gli00001

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