Create a MD5-Hash and Dump as a Hex String

public String md5(String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();
        
        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i=0; i<messageDigest.length; i++)
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        return hexString.toString();
        
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

6 Comments

#
chris - July 13, 2009 at 10:55 a.m.

this is not working!

the java.security package produces strange md5 hashes with 30, 31 or 32 characters. it seems to cut out 0's here and there.

better go for this easy implementation:
http://www.twmacinta.com/myjava/fast_md5.php#download

#
software development uk - August 18, 2009 at 9:56 a.m.

Cool,

so you used a MD5 in a hex string!!! thanks, that was inspiring

Keep up the good work

#
software development uk - August 20, 2009 at 3:16 p.m.

Quite inspiring,

hashing this way can prevent hackers to use the data so easily

Keep up the good work

#
Carl - August 28, 2009 at 10:34 a.m.

This MD5 is not working properly. Chris is correct on this one. I am missing 0s aas well.

#
rost - November 3, 2009 at midnight

the numbers from Integer.toHexString(...) has to be padded so they are always two characters.

in the innerloop you can instead put:

String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length()<2) h = "0" + h;
hexString.append(h);

#
Steve Abrams - November 5, 2009 at 5:51 p.m.

For those missing 0s, looks like rost's post will work. Another example taking care of this is here:
http://www.helloandroid.com/node/159

Add a Comment