1

I am wondering about when to use the managedIv method in the Apex crypto class. I noticed that if I use the managedIv method with a key from the Apex generateAESKey() method my results are always a little bit off.

As an example if I run the following in anonymous Apex it turns "Is this Working" into "Isthisworkin".

Blob key = Crypto.generateAesKey(256);

Blob testString = EncodingUtil.base64Decode('Is this working');

Blob result =  Crypto.encryptWithManagedIV('AES256', key, testString );

System.debug(result);

Blob decryptedBlob = Crypto.decryptWithManagedIV('AES256', key, result);

System.debug(EncodingUtil.base64Encode(decryptedBlob));

But if run it with the Crypto.encrypt() and provide an IV with the same key it works. Can anyone tell me why this is?

1

1 Answer 1

2

It's the encoding that's at fault, not the crypto.

Is this working is not a Base64 string. In fact, if you take testString and try to decode it back to a string, you'll get an error because it doesn't produce valid UTF-8.

If you directly convert blobs to Strings, you'll get the right result:

Blob key = Crypto.generateAesKey(256);

Blob testString = Blob.valueOf('Is this working');

Blob result =  Crypto.encryptWithManagedIV('AES256', key, testString );

System.debug(result);

Blob decryptedBlob = Crypto.decryptWithManagedIV('AES256', key, result);

System.debug(decryptedBlob.toString());

11:42:27:009 USER_DEBUG [11]|DEBUG|Is this working

The fact that it works with an explicit IV and not with a managed IV is not immediately clear to me - possibly the data is being padded differently somewhere such that it accidentally returns the right result? - but the root cause is definitely the use of Base64 where it's not needed.

1
  • Thanks for the great answer, David. Jan 8, 2021 at 19:31

You must log in to answer this question.

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