Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How can I generate an MD5 hash?

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

2 Answers

Kajalsi45d
On the off chance that you really need the appropriate response back as a string instead of a byte exhibit, you could generally accomplish 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;
}
MounikaDasa
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.

Login / Signup to Answer the Question.