Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 7 down vote accepted

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.

share|improve this answer
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 Jun 16 '14 at 10:48
@Adam ... yep to get back to the Blob (binary) data. – Keith C Jun 16 '14 at 10:54

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.