function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yogesh BiyaniYogesh Biyani 

BLOB is not a valid UTF-8 string


 
I would like to save an email as MD5 hash and have the following code which fails with BLOB is not a valid UTF-8 string
 
Blob targetBlob = Blob.valueOf(o.Email__c);
	    Blob hash = Crypto.generateDigest('MD5', targetBlob);
            o.Email__c=hash.toString()+'@somewhere.com';
What do I need to do to remove this error message?

Yogesh
 
Best Answer chosen by Yogesh Biyani
Narender Singh(Nads)Narender Singh(Nads)
Hi Yogesh,

My sincere apologies. I must have misread it.

The reason you are getting this error is because salesforce only accepts UTF-8 format string. But when you encrypt it with MD5 the string no longer remains in UTF-8 format. So you will have to encode it to UTF-8 format.
Like this:
 
Blob targetBlob = Blob.valueOf(o.Email__c);
	    Blob hash = Crypto.generateDigest('MD5', targetBlob);
            o.Email__c=EncodingUtil.base64Encode(hash)+'@somewhere.com';

This should fix your problem.
Let me know if it helps
Thanks! 

 

All Answers

Narender Singh(Nads)Narender Singh(Nads)
Hi Yogesh,

Crypto.generateDigest() accepts a string as input  but you are passing a blob type parameter. That's why you are getting this error.

Try something like this:
Blob targetBlob = Blob.valueOf(o.Email__c);
string hash = Crypto.generateDigest('MD5', targetBlob.tostring());
o.Email__c=hash+'@somewhere.com';

Let me know if it helps
Thanks! 
 
Yogesh BiyaniYogesh Biyani
Hello Narender,

As per the docs (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_crypto.htm) and the example generateDigest accepts a Blob....
 
Blob targetBlob = Blob.valueOf('ExampleMD5String');
Blob hash = Crypto.generateDigest('MD5', targetBlob);


Yogesh
 
Narender Singh(Nads)Narender Singh(Nads)
Hi Yogesh,

My sincere apologies. I must have misread it.

The reason you are getting this error is because salesforce only accepts UTF-8 format string. But when you encrypt it with MD5 the string no longer remains in UTF-8 format. So you will have to encode it to UTF-8 format.
Like this:
 
Blob targetBlob = Blob.valueOf(o.Email__c);
	    Blob hash = Crypto.generateDigest('MD5', targetBlob);
            o.Email__c=EncodingUtil.base64Encode(hash)+'@somewhere.com';

This should fix your problem.
Let me know if it helps
Thanks! 

 
This was selected as the best answer
Yogesh BiyaniYogesh Biyani
Hello Narender,

The latest suggestion works. Thanks. 

Yogesh
Narender Singh(Nads)Narender Singh(Nads)
Hi,
Please mark the best answer so that others facing similar issue can benefit from this post.
Naveen KNNaveen KN
Check the below link

https://www.codekiat.com/2019/06/blob-is-not-a-valid-utf-8-string-salesforce-apex.html