0

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);"

Encryption:

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

Decryption:

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

1 Answer 1

6

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.

3
  • 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. Sep 12, 2017 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, 2018 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, 2018 at 22:25

You must log in to answer this question.

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