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
asadim2asadim2 

Encode a string and view it -error: BLOB is not a valid UTF-8 string

Very simple scenario: take a string, encode it, then display the encoded characters. And it gives this error:

BLOB is not a valid UTF-8 string

 

Code:

Blob key = Blob.valueOf('asdfghjkzxcvbnml'); // 16 bytes
Blob iv = Blob.valueOf('asdfghjkzxcvbnmn'); // 16 bytes
String u = 'X';
Blob uenc = Crypto.encrypt('AES128', key, iv, Blob.valueOf(u));
system.debug(uenc.tostring()); // BREAKS HERE

 

Any ideas why this is happening?! Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
SuperfellSuperfell

Then you need a final step to convert the blob (binary data) into a string, checkout the EncodingUtil class.

All Answers

sfcksfck

I think this is normal. The encryption process does calculations on binary data and produces more binary data. The resulting encrypted data may contain bytes that do not correspond to characters and therefore cannot be converted to a string. If you decrypt it back again, that's when you want it to be viewable as a string. The encrypted data just gets stored as binary so it doesn't matter.

asadim2asadim2

I wanted to store passwords inside Custom Settings, that's why I wanted to encrypt using a pre-defined key/IV and store the string version in there, so then later on I could decrypt and use them.

SuperfellSuperfell

Then you need a final step to convert the blob (binary data) into a string, checkout the EncodingUtil class.

This was selected as the best answer
asadim2asadim2

Thanks to both Naomi and Simon. The base64encode/decode methods were what I needed!