I am encrypting a message using Crypto class methods. I have created a key as follows:

Blob cryptoKeyBlob = Crypto.generateAesKey(128);
String cryptoKeyString = EncodingUtil.base64Encode(cryptoKeyBlob);

I have stored this key in a custom setting. For encryption, I do the following:

Blob cryptoKeyBlob = EncodingUtil.base64Decode(setting.Crypto_Key__c);
Blob msgBlob = Blob.valueOf('my message to be encrypted');
Blob encryptedMsgBlob = Crypto.encryptWithManagedIV('AES128', cryptoKeyBlob, msgBlob);
String encryptedMsgString = EncodingUtil.base64Encode(encryptedMsgBlob);

The decryption is done as follows:

Blob cryptoKeyBlob = EncodingUtil.base64Decode(setting.Crypto_Key__c);
Blob encryptedMsgBlob = EncodingUtil.base64Decode(encryptedMsgString);
Blob decryptedMsgBlob = Crypto.decryptWithManagedIV('AES128', cryptoKeyBlob, encryptedMsgBlob);
String decryptedMsgString = decryptedMsgBlob.toString();

However during the decryption, it shows an error saying: Input length must be multiple of 16 when decrypting with padded cipher

When I check the debug logs the key Blob is 16 bit i.e. Blob[16]. Isn't 16 a multiple of 16? If I hard code the key string in the encryption and decryption process it works. I do not understand what am I doing wrong.

Any help will be appreciated.

Your Answer

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

Browse other questions tagged or ask your own question.