The below code works sometimes and sometimes it gives an error. The error is like this. Input length must be multiple of 16 when decrypting with the padded cipher. I am getting an error in decryption on the 3rd line of Decryption. "Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData);"


Blob cryptoKey = EncodingUtil.base64Decode(privateKeyValue);
Blob data = Blob.valueOf(String.escapeSingleQuotes(dataToEncrypt));
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
String encryptedDataString = EncodingUtil.base64Encode(encryptedData);


Blob cryptoKey = EncodingUtil.base64Decode(privateKeyValue);
Blob encryptedData = EncodingUtil.base64Decode(String.escapeSingleQuotes(encryptedValue));
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData);
String decryptedDataString = decryptedData.toString();

The following code works in my org.

Blob key = Crypto.generateAesKey(256);

Blob source = Blob.valueOf('Hello World');
Blob encrypted = Crypto.encryptWithManagedIV('AES256', key, source);
String encrypted64 = EncodingUtil.base64Encode(encrypted);

Blob dest = EncodingUtil.base64Decode(encrypted64);
Blob decrypted = Crypto.decryptWithManagedIv('AES256', key, dest);
String decryptedText = decrypted.toString();

I suspect that somehow using String.escapeSingleQuotes might randomly cause this issue. You should not be escaping any special characters, because it is not necessary.

  • Thanks for your quick reply. I removed the String.escapeSingleQuotes. But still, it is not working sometimes. When I try to decrypt that encrypted id in site page controller, I am getting an error. "Input length must be multiple of 16 when decrypting with padded cipher" It works fine when I decrypt same data in the developer console. – Ghanshyam Kumar Sep 12 '17 at 6:59
  • I have a quick question regarding the algorithm. As I know we have use the same key to encrypt and decrypt the text, so part from storing the same in custom setting or any label. Is thier any other way we can do it in run time. I have a scenario where the encryption and decryption happens on different transactions not in same transactions hence in the code I Ccant use the same. So wanted to know if there is any other possible way – Abhik Dey Jan 4 '18 at 21:17
  • @AbhikDey This is addressed in other questions here on SFSE, but basically, after generating the key, you store it in a persistent place, such as in a Custom Setting or an SObject somewhere. There's a variety of choices to choose from. – sfdcfox Jan 4 '18 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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