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
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With