4

I write a simple function to convert string to md5 and i see weird letters in the output. I assume some character encoding is messed up. Can i some one point what i am doing wrong?

public class App 
{   
public static void main(String[] args){
    String str = "helloWorldhelloWorldhelloWolrd";
    getHash(str);

}

public static void getHash(String str){
    try {
        byte[]  three = str.getBytes("UTF-8");
        MessageDigest   md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(three);
        String  str1 = new String(thedigest,"UTF-8");
        System.err.println(str1);
    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();
    }catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    }
}

}

OUTPUT: This is what i see

                                n?)?????fC?7
1
  • 2
    FWIW, if you can use third-party libraries, Guava can get you hex-encoded MD5 hash in the one-liner with Hashing.md5().hashString(string, Charsets.UTF_8).toString(). Mar 18, 2013 at 19:55

2 Answers 2

7

You need to convert the bytes to a Hex string rather than straight to a String:

byte[] thedigest = md.digest(three);
StringBuilder buff = new StringBuilder();
for (byte b : theDigest) {
  String conversion = Integer.toString(b & 0xFF,16);
  while (conversion.length() < 2) {
    conversion = "0" + conversion;
  }
  buff.append(conversion);
}
String str1 = buff.toString();
System.err.println(str1);
5
  • 2
    This won't work, quite. You have to worry about negative bytes, which means that you have to do b & 0xFF, and then you have to worry about padding, because some bytes will get encoded as one character without a leading zero. Mar 18, 2013 at 19:57
  • This is what I use: final BigInteger bigInt = new BigInteger(1, md.digest()); String.format("%032x", bigInt); Mar 18, 2013 at 19:58
  • @LouisWasserman Negative bytes will be in two's complement format no? Mar 18, 2013 at 19:59
  • With your change i see this 6e-6329-647f-7f-22-47-42-5210661143-3837
    – javaMan
    Mar 18, 2013 at 20:00
  • Thx. to Jason's comment as well. Jun 7, 2015 at 15:10
2

You can't display the digest as a String, (because it's only rubbish) you need to translate the bytes somehow so you can display them in a human readable form. I would propose a Base64 encoder.

There is another thread discussing how to convert a MD5 into a String here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.