I get an encrypted data from external service (AWS Cognito). With the following code, I get the 'Invalid private key. Must be 16 bytes' error.
String data = 'qgBYrFjDvnS5yb1ZWtP2yfbO6CU7ezVNXq6MlXRLAZmgiCNBUfXfSq+2yBvfHdv9a3HV+mGsT8SMIpeWQ/yuzibMwI7xTgObjMU8vfz8AMXI1p/RRdTPPSNmz0kMy/MHdRoKVBG0Tl+OthYXP+dxDlCQEe1cJyLnoMd43OJ3m22Mf3EMboSEeH2Pzq6T0M92T2tNKyBT7CvsV5w2p4/4ZDWAs6vj3nHAWyKNoai5w/O7sGAbI1iOr3EqkAfgwaSjFyTZ7bgznd9II6vM0L0xCS76tZ/WcJrVcl2vtQKVOSfmw6/T+52ZePYWLnsB94y0eLEWNdASgz13P36m9jzaBvzA/HB3gxfligCEHjSXjeqwmHjvE3NKSsMH0aDY6c4Rj6ecPOvqGymbkfjY9kxfV7RHFYl/fwXoIRGxNZnDlNpNqDZ9UZ3lJHLDDUcHX8xc4W2IQPHyKb0SW09fXNhHxYgb7j0eS83P/BFy6GfWU+1K7Xk8lRnLtHhdPbAjiOWlWRG+S37nEX9gJBHlgYi/dVaCOFyq1hkVDuoIJiZ6rJvVYIIbhxsF1SJN8TTU723ynSIq40lzVEuz1QZp9qtV/aa3Sh5dMBZlyGDAS4hy6VL9APFlCbwL4XhyKetvUtdzI/Z+nmJi/SlyA9HIxS5L7LQYMGtamJvkeB1T+EM+Sn+6holTXUvS/ehliDYggcSVFqhVAWUb4pKyujsvTyg2Ej3GPAdwu30hI6dZA3gjConOOWfOHOuBkOc+bbcT6J7whoDma1nvwA837E9uAvfuP7cquiB2G1q/VCW0Whuy8D1PEIbIdrB4iXNZuDIIvEiNKufQ2SCyau2mpIVuoPhLgsf4OKiPNv4mYuyJf6E6Ui3FgH6i/T7xfRH8W0nzu2vmBkYkBy5cPAx5+lp3Dm1lYwDuXYyls0/aBPXOjo968Z3dop5ZFlB/ZfaTgL8TKkj9wnVvbfasNm6fowFR1bqsSi5msK23VRA79/gNPOBtJZViynUaZzkPsQtxB893W8iDZnhrF54FPi7NrKkpFHmZCCd8mkbtOXJAyntVExlY5F9zCJlWtQdzGvfDew8PEYlo3LIubFeDGP7S6nCoOlG8zRyMDdKrmM6mOJaCFceJlFJ/yqnSd197+dqqY+MyQ+WWge70y+2jmYxZm9fJSuODskKkz9cas/TuxDvTaE2bKm1Q4udLwUDjB8yDxZvkGVm0e91hEMosgdqZ626zBk3GvD1wYMDT995AVx3XQbGGpUmwBwoFvdWRdf0hKMr3yEaCsDmAnftSzzKYRc33SbNkWEkSA7KCCG0u6KUIisfn1v487rEy+ozTp6eX8gluHpxVBLAD21DJXPrDmQGDc9vbSg==';
String key = '75ac5e7677e7218a7f059f0bda073a6b';
Blob dataB = EncodingUtil.base64Decode(data);
Blob keyB = Blob.valueOf(key);
Blob decryptedData = Crypto.decryptWithManagedIV('AES128', keyB, dataB);
String decryptedDataString = decryptedData.toString();
I also have an example of implementation of decryption with Javascript, but cannot decrypt it with Apex.
function decryptEncryptedResponse(data, key) {
if (typeof data === 'string') {
var byteCharacters = atob(data);
var iv = new Array(16);
var crypttext = new Array(byteCharacters.length - 16);
for (var i = 0; i < byteCharacters.length; i++) {
if (i < 16) {
iv[i] = byteCharacters.charCodeAt(i);
} else {
crypttext[i - 16] = byteCharacters.charCodeAt(i);
}
}
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: byteArrayToWordArray(crypttext)
});
var plaintextArray = CryptoJS.AES.decrypt(
cipherParams,
CryptoJS.enc.Hex.parse(key),
{iv: byteArrayToWordArray(iv), mode: CryptoJS.mode.CBC, keySize: 128}
);
return JSON.parse(CryptoJS.enc.Latin1.stringify(plaintextArray));
} else {
return data;
}
}
How can I do the same with Apex? Thank you in advance!
UPDATE Thank you for help! The final alternative method below:
public String decryptEncryptedResponse(String data, String key) {
Blob dataB = EncodingUtil.base64Decode(data);
Blob keyB = EncodingUtil.ConvertFromHex(key);
Blob decryptedData = Crypto.decryptWithManagedIV('AES128', keyB, dataB);
return decryptedData.toString();
}