I had given an cipher text (of JSON string), an IV and a key. I tried decrypting using Apex Crypto class's method:
decryptWithManagedIV(algorithmName, privateKey, IVAndCipherText)
//Sample code
Blob key = Blob.valueOf(decryptionKey);
Blob encryptedDatafor = EncodingUtil.base64Decode(bodystring);
Blob decryptedData = Crypto.decryptwithManagedIV('AES128', key, encryptedDatafor);
cipher = decryptedData.toString();
System.debug('Encrypted BodyString: ' +cipher);
and I was able to decrypt the cipher successfully. But when I use the provided IV with the following method:
decrypt(algorithmName, privateKey, initializationVector, cipherText)
//Sample code
Blob exampleIV = Blob.valueOf('HSDlUkhrmfEo7SgM'); //provided IV
Blob key = Blob.valueOf(decryptionKey);
Blob encryptedDatafor = EncodingUtil.base64Decode(bodystring);
Blob decryptedDataIV = Crypto.decrypt('AES128', key, exampleIV, encryptedDatafor);
cipher = EncodingUtil.base64Encode(decryptedDataIV );
System.debug('Encrypted BodyString: ' +cipher);
I get some string which looks like, it is still in the encrypted form (different from the encrypted string I have passed).
Update: I have tried the below code-snippet based on the suggestion from @identigral, but I am still unable to decrypt the cipher using the IV:
Blob exampleIV = Blob.valueOf('HSDlUkhrmfEo7SgM'); //provided IV
Blob key = Blob.valueOf(decryptionKey);
Blob encryptedDatafor = EncodingUtil.base64Decode(bodystring);
String encodedCipherTextAndIV = EncodingUtil.convertToHex(encryptedDatafor);
String encodedCipherText = encodedCipherTextAndIV.substring(32);
String finCipher = encodedCipherText.difference(encodedCipherTextAndIV);
Blob ciphertext = EncodingUtil.convertFromHex(finCipher);
Blob decryptedDataIV = Crypto.decrypt('AES128', key, exampleIV, ciphertext);
decryptStg = EncodingUtil.base64Encode(decryptedDataIV );
System.debug('Decrypted BodyString: ' +decryptStg);
bodystring? Do I need to delete the first 16 characters from thebody? If so, I did that too. And I get an error that says:System.SecurityException: last block incomplete in decryption. Any workaround? – SatyaV Jul 30 '19 at 15:35ciphertextis actually the IV bytes, right (first 16 bytes)? Correct me if I am wrong. I am guessing this as I am still getting some encrypted text. – SatyaV Jul 30 '19 at 16:15encodedCiphertextconvert too? Does it extract the substring after 32nd character, making it separate from the IV? I understood the string function you did forIV. – SatyaV Jul 30 '19 at 17:48encodedCiphertextis the substring after the 32nd character, yes. – identigral Jul 30 '19 at 17:49