We have an Apex method in our Org which is exposed for a GET API request. The data is encrypted with AES256 before sending. However from the receiver end (Same Org for testing purpose), decryption of the data is failing with error System.SecurityException: Input length must be multiple of 16 when decrypting with padded cipher
I have checked the IV, key and the AlgorirthmName at both Sender and Receiver end. It's not an issue with the format or a conflict in their values ( Tried them without the API calls and it was successful). I am assuming that the Data Integration is getting corrupted in the API transit OR is the encrypted data itself needs to be in multiples of 16 bytes? If so, how to do that? Did anyone else have the same issue? Or anyway to debug it?
Below sample code
Sender Apex Class
@RestResource(urlMapping='/sampleMethod/Opportunities/*')
global with sharing class OpportunityInfo{
@HttpGet
global static void getOpportunities() {
RestResponse res = RestContext.response;
List<Opportunity> optydata = [Select Id, Name from Opportunity LIMIT 100];
Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(256);
Blob data = Blob.valueOf(JSON.serialize(optydata));
Blob encrypted = Crypto.encrypt('AES256', key, exampleIv, data);
res.ResponseBody = encrypted;
res.statusCode = 200;
}
}
Receiver Apex Class
public class sampleReceiverClass{
HttpRequest request2 = new HttpRequest();
request2.setEndpoint('https:// <orgURL>/services/apexrest/sampleMethod/Opportunities');
request2.setMethod('GET');
request2.setHeader('Authorization', 'Bearer ' + accessToken); // Access Token received
//from a different method, not shown here
Http http2 = new Http();
HttpResponse response2 = http2.send(request2);
system.debug('response2 getbody=='+response2.getStatusCode()); // Status code is 200
Blob encrypteddata = Blob.valueOf(response2.getbody());
// Blob encrypteddata = response2.getBodyAsBlob(); // This works!!
String initializationVector = <IV String>;
String encrytpionKey = <Key>;
String algorithmName = 'AES256';
Blob keyBlob = EncodingUtil.base64Decode(encrytpionKey);
Blob IV = Blob.valueOf(initializationVector);
Blob decrypted = Crypto.decrypt(algorithmName, keyBlob, IV, encrypteddata); // Getting Error here
}
EncodingUtil.base64Decode, it decrypts for us. – identigral Oct 27 '23 at 15:24