Search code examples
javamd5digest

Java MessageDigest doesn't work


I can't make MessageDigest work, the program gives me two error: UnsupportedEncodingException, NoSuchAlgorithmException

 byte[] bytesOfchat_key = "lol".getBytes("UTF-8");
 MessageDigest md = MessageDigest.getInstance("MD5");
 byte[] Digest = md.digest(bytesOfchat_key);

If I throw the errors, it give me ワ￟ᄡ9ᅦヌnp>0xd￉z as response ( 16 chars )

PS: I have used to print the Digest

for (byte b : Digest) {
    System.out.print((char)b);
}

Solution

  • md5 returns hexadecimal numbers, so for decoding it to a String you could use

    String plaintext = "lol";
    MessageDigest m = MessageDigest.getInstance("MD5");
    m.reset();
    m.update(plaintext.getBytes());
    byte[] digest = m.digest();
    //Decoding
    BigInteger bigInt = new BigInteger(1,digest);
    String hashtext = bigInt.toString(16);
    while(hashtext.length() < 32 ){
      hashtext = "0"+hashtext;
    }