MD5 Blob Cannot Convert to String

Instead of toString, you need to actually use EncodingUtil.convertToHex to get the output you expect:

String myString = 'Some String';
system.debug(myString);
Blob myBlob = Blob.valueOf(myString);
system.debug(myBlob);
Blob md5hash = Crypto.generateDigest('MD5', myBlob);
System.debug(md5hash);
System.debug(EncodingUtil.convertToHex(md5hash));

Blob#toString ties to convert the binary data directly into a UTF-8 compatible string (which would be 16 characters long). However, since one or more bytes are likely to be illegal UTF-8 characters, you end up getting this error.

The EncodingUtil.convertToHex method, by contrast, converts the binary data into a format where each byte is converted to 2 bytes, using values from 0-9 and a-f, the hexadecimal numbering system. This is the same format that all other major users of md5 and crypto in general would expect to receive.


This is a useful cryptography helper class I often use:

public class CryptoUtils {

    public static String SHA1Hash(String value) {
        return hash('SHA1', value);
    }

    public static String MD5Hash(String value) {
        return hash('MD5', value);
    }

    public static String SHA256Hash(String value) {
        return hash('SHA-256', value);
    }

    public static String SHA512Hash(String value) {
        return hash('SHA-512', value);
    }

    private static String hash(String algorithmName, String input) {
        return EncodingUtil.convertToHex(Crypto.generateDigest(algorithmName, Blob.valueOf(input)));
    }
}

Tags:

Blob

Apex

Crypto