Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java md5 hash showing garbage

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
like image 656
javaMan Avatar asked Jan 13 '23 22:01

javaMan


2 Answers

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);
like image 127
Chris Cooper Avatar answered Jan 19 '23 10:01

Chris Cooper


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.

like image 39
GameDroids Avatar answered Jan 19 '23 12:01

GameDroids