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?

Brooks Johnson
  • 1,443
  • 2
  • 21
  • 37
  • See https://salesforce.stackexchange.com/questions/271648/encrypting-and-or-decrypting-ciphertext-with-the-provided-initialization-vector for an example – identigral Jan 08 '21 at 18:45

1 Answers1

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.

David Reed
  • 92,733
  • 13
  • 84
  • 157