I'm getting the error when I'm trying to decrypt an encrypted value in line 7.

Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf(randStr);
Blob encrypted = Crypto.encrypt('AES128', key, exampleIv, data);
Con.Password__c = String.valueOf(encrypted);

Blob Passwrd = Blob.valueOf(Con.Password__c);
Blob decrypted = Crypto.decrypt('AES128', key, exampleIv, Passwrd);
String decryptedString = decrypted.toString();

Can someone suggest how I convert string to Blob?

1 Answer 1


String.valueOf accept Blob as input considering it as an Object and I'm not sure which encoding type is used during the conversion of blob to string. On the other hand, I guess Blob.valueOf expects an UTF-8 encoded string. Getting into the details of this is probably beyond the scope of this question.

So in your code, the conversion of blob - string - blob is possibly losing some bytes of data required by the Crypto.decrypt method, there by leading to System.SecurityException. Consider using EncodingUtil methods for conversion of string to blob and vice-versa (using base64).

You will have to replace

Con.Password__c = String.valueOf(encrypted);
Blob Passwrd = Blob.valueOf(Con.Password__c);


Con.Password__c = EncodingUtil.base64Encode(encrypted);
Blob Passwrd = EncodingUtil.base64Decode(Con.Password__c);
  • thank you, it works. Commented May 30, 2022 at 9:22

You must log in to answer this question.

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