How can I generate an MD5 hash in Java? How can I generate an MD5 hash in Java? java java

How can I generate an MD5 hash in Java?


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.


You need java.security.MessageDigest.

Call MessageDigest.getInstance("MD5") to get a MD5 instance of MessageDigest you can use.

The compute the hash by doing one of:

  • Feed the entire input as a byte[] and calculate the hash in one operation with md.digest(bytes).
  • Feed the MessageDigest one byte[] chunk at a time by calling md.update(bytes). When you're done adding input bytes, calculate the hash with md.digest().

The byte[] returned by md.digest() is the MD5 hash.


If you actually want the answer back as a string as opposed to a byte array, you could always do something like this:

String plaintext = "your text here";MessageDigest m = MessageDigest.getInstance("MD5");m.reset();m.update(plaintext.getBytes());byte[] digest = m.digest();BigInteger bigInt = new BigInteger(1,digest);String hashtext = bigInt.toString(16);// Now we need to zero pad it if you actually want the full 32 chars.while(hashtext.length() < 32 ){  hashtext = "0"+hashtext;}