java – Transform MessageDigest MD5 into string

Question:

I'm trying to generate an MD5 hash using the MessageDigest class, however, I can't correctly display the hash as a string on the screen. The result is a string of unknown characters.

Below is the test code:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author 
 */
public class TesteMD5
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {

       String str = "teste md5";

       try{
          MessageDigest md = MessageDigest.getInstance("MD5");
          md.update(str.getBytes());
          byte[] bytes = md.digest();
          System.out.println("Hash: " + new String(bytes));
       }catch(NoSuchAlgorithmException e){
          e.printStackTrace();
       }
    }
}

The result I'm getting is:

Hash: ���9��p>n$�u �

Answer:

You are returning the string representation of the bytes returned by the MessageDigest method.

The code to represent what you want is this:

    String original = "teste md5";

    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(original.getBytes());
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer();

        for (byte b : digest)
            sb.append(String.format("%02x", b & 0xff));

        System.out.println("string original: " + original);
        System.out.println("digested(hex): " + sb.toString());
    } catch(NoSuchAlgorithmException e){
        e.printStackTrace();
    }

You can see and run this example here: jdoodle.com/a/Yi

The output will be:

string original: teste md5
digested(hex): d4d1c93999f913703e6e0524b17520ef

Source: http://www.avajava.com/tutorials/lessons/how-do-i-generate-an-md5-digest-for-a-string.html

Scroll to Top