How can I generate an MD5 hash?

Akshay picture Akshay · Jan 6, 2009 · Viewed 1M times · Source

Is there any method to generate MD5 hash of a string in Java?

Answer

koregan picture koregan · Jan 6, 2009

The MessageDigest class can provide you with an instance of the MD5 digest.

When working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use string.getBytes() it will use the platform default. (Not all platforms use the same defaults)

import java.security.*;

..

byte[] bytesOfMessage = yourString.getBytes("UTF-8");

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);

If you have a lot of data take a look at the .update(byte[]) method which can be called repeatedly. Then call .digest() to obtain the resulting hash.