How can I generate an MD5 hash in Java?
Is there any method to generate MD5 hash of a string in Java?
Solution 1:
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[] theMD5digest = md.digest(bytesOfMessage);
If you have a lot of data take a look at the .update(xxx)
methods which can be called repeatedly. Then call .digest()
to obtain the resulting hash.
Solution 2:
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 withmd.digest(bytes)
. - Feed the
MessageDigest
onebyte[]
chunk at a time by callingmd.update(bytes)
. When you're done adding input bytes, calculate the hash withmd.digest()
.
The byte[]
returned by md.digest()
is the MD5 hash.
Solution 3:
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;
}
Solution 4:
You might also want to look at the DigestUtils class of the apache commons codec project, which provides very convenient methods to create MD5 or SHA digests.
Solution 5:
Found this:
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
on the site below, I take no credit for it, but its a solution that works! For me lots of other code didnt work properly, I ended up missing 0s in the hash. This one seems to be the same as PHP has. source: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093