I could sit and mess around with this but I really don't know the finer points of how cryptography works in Java/Apex to risk sitting on a security hole.

Basically I'm creating a hash and then storing it, but I'm getting an error when I try and cast the blob object returned by the hash function to a string.

Here's my code:

String valueToHash = sfMessage.My_String__c + String.valueOf(sfMessage.My_Date__c);
sfMessage.Hashed_String__c = Crypto.generateDigest('SHA-256', Blob.valueOf(valueToHash)).toString();

And the error I'm getting is a System.StringException telling me that in the second line "BLOB is not a valid UTF-8 string.

So how do I end up with a plain text representation (in whatever encoding Salesforce uses) of my hashed value? Also I've got the field length at 64 chars long, is this enough?

1 Answer 1


You need to turn the digest bytes into a valid string first and one way to do that is to base64 encode:

Blob b = Crypto.generateDigest('SHA-256', Blob.valueOf(valueToHash));
sfMessage.Hashed_String__c = EncodingUtil.base64Encode(b);

You will have to do the base 64 decode before using the digest too.

See EncodingUtil.

  • Ah brilliant :) thank you. So later when I come to check a hash against this one I need to do base64Decode(string) on the stored value?
    – Adam
    Commented Jun 16, 2014 at 10:48
  • @Adam ... yep to get back to the Blob (binary) data.
    – Keith C
    Commented Jun 16, 2014 at 10:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .