-1

I wonder why my string after the md5 transfer, output sth contains many unreadable characters, such as ? .etc. In this case the code below outputs ���kh{��j��p%�.

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;



public class Test{
    public static void main(String args[]){


        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            String ssmd5 = "sp00";
            String ShipmentID = new String(md.digest(ssmd5.getBytes()), StandardCharsets.UTF_8);
            System.out.println(ShipmentID);

        }catch(NoSuchAlgorithmException e){
            System.out.println("I'm sorry, but MD5 is not a valid message digest algorithm");
        }



    }
}
michael
  • 39
  • 7
  • 3
    `MessageDigest.digest` returns a `byte[]`; you're trying to convert it to a `String`, which is logically a `char[]`. `char` and `byte` aren't the same thing. If you want to print it as a readable string, base64 encode the bytes (or print the bytes as hex). – Andy Turner Jul 26 '16 at 22:14

1 Answers1

2

The output of the MD5 digest function is a binary sequence of bytes, not a printable character string.

It is not possible to print a raw MD5 digest.

If you want to print a human-readable representation of the digest, you should print it as hexadecimal or BASE64 encoded string.

See: How to convert a byte array to a hex string in Java?

Community
  • 1
  • 1
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190