Storing hash values (blob) in a string field?

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?

Answer

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.

Attribution
Source : Link , Question Author : Adam , Answer Author : Keith C