tags:

views:

132

answers:

5
+1  Q: 

MD5 format in Java

Possible Duplicate:
Generate MD5 hash in Java

Can some one tell me how to convert a string into MD5 format in Java?

I have code like this, but I want in MD5 format with 32 characters.

UUID uuid = UUID.randomUUID();
String token = uuid.toString().substring(0,12);
A: 

quite easy just us a MessageDigester:

    MessageDigest digest=MessageDigest.getInstance("MD5");
    StringBuilder hexBuilder=new StringBuilder();
    byte[] md5=digest.digest("test".getBytes(Charset.defaultCharset()));
    for (int i=0; i < md5.length; i++) {
        hexBuilder.append(Integer.toString( ( md5[i] & 0xff ) + 0x100, 16));
      }
    System.out.println(hexBuilder.toString());
smeg4brains
Is it worth specifying an encoding in your call to `String.getBytes()`?
Alison
Not only that, it is also not converting to hex.
BalusC
Good point; I missed that.
Alison
christ, one shouldnt write so fast...ill fix the answer
smeg4brains
should work now...
smeg4brains
`String.getBytes(Charset.defaultCharset())` is the same as `String.getBytes()`, and may have different results on different platforms.
Alison
A: 

Implemenation

import java.security.MessageDigest;
import java.math.BigInteger;
import java.lang.String

public class SecurityUtil {

  public static String stringToMD5(String string) throws NoSuchAlgorithmException {

    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    messageDigest.update(string.getBytes(Charset.forName("UTF-8")),0,string.length());
    return new BigInteger(1,messageDigest.digest()).toString(16);
  }
}

Usage:

  System.out.println(String.format("MD5: %s", stringToMD5("P@$$\\/\\/R|)")));

Output:

MD5: 91162629d258a876ee994e9233b2ad87*

In this sample was used the coding UTF-8.

What is Charset ?
What is MessageDigest ?
What is UTF-8 >

*md5 is example from Wikipedia.

Vash
Is it worth specifying an encoding in your call to `String.getBytes()`?
Alison
A: 

This worked for me..

UUID uuid = UUID.randomUUID();
String token = MD5.digest(uuid.toString().substring(0,12));

thanks for all the answers guys.

salman
A: 

I got bored again...

/**
 * @author BjornS
 * @created 2. sep. 2010
 */
public enum HashUtil {

    SHA1("SHA1"), MD5("MD5"), MD2("MD2"), SHA256("SHA-256"), SHA384("SHA-384"), SHA512("SHA-512");

    private final MessageDigest digester;

    HashUtil(String algorithm) {
        try {
            digester = MessageDigest.getInstance(algorithm);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e.getMessage(), e);
        }
    }

    public String hash(byte[] in) {
        return toHexString(digester.digest(in));
    }

    public String hash(String in) {
    return hash(in.getBytes());
    }

    public String hash(String in, Charset characterSet) {
        return hash(in.getBytes(characterSet));
    }

    public byte[] hashToByteArray(String in) {
        return digester.digest(in.getBytes());
    }

    public byte[] hashToByteArray(String in, Charset characterSet) {
        return digester.digest(in.getBytes(characterSet));
    }

    public byte[] hashToByteArray(byte[] in) {
        return digester.digest(in);
    }

    private String toHexString(byte[] digest) {
        StringBuffer hexStr = new StringBuffer(40);
        for (byte b : digest) {
            hexStr.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        }
        return hexStr.toString();
    }

}

-

/*** ***/
// Use Charsets from Google Guava rather than manually code the charset request, you also don't have to catch exceptions this way! :)

pulic static void main(String... args) {
    UUID uuid = UUID.randomUUID();
    String uuidString = uuid.toString().substring(0,12);
    String token = HashUtil.MD5.hash(uuidString,Charsets.UTF_8);
}
BjornS
You missed the comments about character encoding on other answers? I'd fix it to UTF-8 (if your application is already designed for world domination) or at least pass it as method argument.
BalusC
I guess I did. Could add it as an optional parameter for the hash method.
BjornS