tags:

views:

117

answers:

3

Hi! I know that there is a lot of similar topics, but still... can someone provide me a working example of method which generates MD5 String.
I'm currently using MessageDigest, and I'm doing the following to get a string

BASE64Encoder().encode(messageDigest.digest())  

I guess there is some better way to do that.
Thanks in advance!

+2  A: 
import java.math.*;
import java.security.*;

String toEnc = "Encrypt This!"; // Value to encrypt
MessageDigest mdEnc = MessageDigest.getInstance("MD5"); 
mdEnc.update(toEnc.getBytes(), 0, toEnc.length());
String md5 = new BigInteger(1, mdEnc.digest()).toString(16) // Encrypted 
org.life.java
FYI: MD5 is a hashing algorithm, not a cipher. Therefore, it does not *encrypt* data. Rather, it *hashes* data.
Adam Paynter
Thanks! Works fine for me
Andrew
@Adam Paynter Thanks, I have edited the comment
org.life.java
@Andrew You can always accept it as answer by clicking a right tick sign near to answer if this is your answer actually.
org.life.java
You do not really need the overhead of creating a BigInteger in order to print a MD5 string. Printing out 16 bytes as hex is not that difficult. Also you might want to edit the source code, as Adam Paynter pointed out, MD5 is not encrypting, but hashing your data.
Grodriguez
+1  A: 

I'd use commons-codec

  • Base64 - Base64.encodeBase64(digestBytes)
  • Hex-string - Hex.encodeHex(digestBytes)
Bozho
A: 
// Convert to hex string
StringBuffer sb = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
    sb.append(Integer.toHexString(0xff & messageDigest[i]));
}
String md5 = sb.toString();

This assumes you actually want your MD5 printed as an hex string, not BASE64-encoded. That's the way it is normally represented.

Grodriguez