0

I am facing an issue while decryption of value which is stored in custom setting. When i encrypt and decrypt value at same time then i that error is not thrown, if i get the value from custom setting, this error is thrown.

below is my code while does not gives error:

Blob cryptoKey = Crypto.generateAesKey(256);

        Blob data = Blob.valueOf('[email protected]');
        Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
        system.debug('encryptedData :' + encryptedData);
        String encryptString = EncodingUtil.base64Encode(encryptedData);
        system.debug('encryptedData 2:' + encryptString);



        Blob data2 = EncodingUtil.base64Decode(encryptString);
        Blob decryptedUsername = Crypto.decryptWithManagedIV('AES256', cryptoKey, data2);
        String decryptedClearText = decryptedUsername.toString();
        System.debug(decryptedClearText);

Below code when i get the value from custom setting:

Blob cryptoKey = Crypto.generateAesKey(256);

        ConnectTranslationAPI__c connect = ConnectTranslationAPI__c.getValues('GenerateToken');
        String username = connect.Username__c;
        username = username.trim();
        System.debug(username);

        Blob data2 = EncodingUtil.base64Decode(username);
        Blob decryptedUsername = Crypto.decryptWithManagedIV('AES256', cryptoKey, data2);
        String decryptedClearText = decryptedUsername.toString();
        System.debug(decryptedClearText);

I tried replace the value in custom setting with the new encryption key. still i get this error

Can you please help me out.

1
  • Please do not use the [community] tag unless you are asking a question about the Communities feature.
    – Adrian Larson
    Feb 13, 2019 at 15:40

1 Answer 1

3

One of two things, I believe, is happening here.

If your code as shown in your question is exactly what you're using, the problem is that you're generating a brand-new AES key every time you try to access an encrypted value.

Blob cryptoKey = Crypto.generateAesKey(256);

That won't work. If you encrypt Value A with Key B to yield Ciphertext C, you have to store and reload Key A in order to decrypt Ciphertext C. Some other Key Q that you generate has no relationship to that ciphertext - that's the whole point of encryption.

The other possibility is that you are correctly storing and using a single key, but the code that stores encrypted values (which you haven't shown here) is either mangling or truncating the ciphertext. I previously wrote an answer demonstrating how such errors arise from ciphertext corruption.

1
  • It was the Key issue. I din't realized that every time it used to generate a new key. Storing the key as well now. Thank you. Feb 14, 2019 at 10:38

You must log in to answer this question.

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