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
Violet AdminViolet Admin 

Key for encryption/decryption works differently when directly used in code vs when stored in custom setting.

I am encrypting a message using  Crypto.decryptWithManagedIV() method. Let my key be:   Wr/wa0vAe9RNmiMr 
This is the encryption and decryption process:
 
Blob cryptoKeyBlob = Blob.valueOf('Wr/wa0vAe9RNmiMr');
Blob msgBlob = Blob.valueOf('my message to be encrypted');
Blob encryptedMsgBlob = Crypto.encryptWithManagedIV('AES128', cryptoKeyBlob, msgBlob);
String encryptedMsgString = EncodingUtil.base64Encode(encryptedMsgBlob);
 
Blob keyBlob = Blob.valueOf('Wr/wa0vAe9RNmiMr');
Blob encryptedMsgBlob = EncodingUtil.base64Decode(encryptedMsgString);
Blob decryptedMsgBlob = Crypto.decryptWithManagedIV('AES128', keyBlob, encryptedMsgBlob);
String decryptedMsgString = decryptedMsgBlob.toString();

The encryption code lives in a different class and so does the decryption code.

Here is the issue. When I directly use the key in the code it works. But since referring a key in the code is not a good process I am using a custom setting to store it. But when the key is read from the custom setting and used in the code it throws an error saying: 
Input length must be multiple of 16 when decrypting with padded cipher

I debugged the code and it seems the key is read as it is and there is no change. I do not understand what is going wrong. Any help will be much appreciated.
KevinPKevinP
have you tried trim() ing the retrieved custom setting? how are you retrieving it? additionally, have you tried doing String.valueOf(customSettingVersion); 
Violet AdminViolet Admin
I just implemented the trim() function for the custom settings but it still does not work. I am retrieving the custom setting using Custom__c setting - Custom__c.getOrgDefaults(); String key = setting.Crypto_Key__c();