I'm wanting to encrypt a byte[] in a C# api endpoint and decrypt the byte array in an Angular 14 app to get the base64 version of the decrypted document so I can provide it to a pdf viewer so I can view the document in the browser.
I followed this [https://stackoverflow.com/questions/63598208/encryption-in-asp-net-core-and-decryption-in-angular/75637618#75637618]. I WAS ABLE to get this to work with a simple string value, but I cannot get the decryption to work with a byte array coming from the api.
SERVER SIDE ENCRYPTION:
{bytesToEncrypt} is the byte array of a binary file I am pulling out of Sharepoint
{key} is the secret key I'm using to encrypt with
public byte[] EncryptAESData(byte[] bytesToEncrypt, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] iv = new byte[16];
byte[] encryptedBytes = new byte[0];
using (Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.IV = iv;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToEncrypt, 0, bytesToEncrypt.Length);
}
encryptedBytes = ms.ToArray();
}
}
//return encrypted string as base64
return encryptedBytes;
}
CLIENT-SIDE DECRYPTION:
{key} the same key used to encrypt the byte array in the API
{bytesToDecrypt} the encrypted byte array coming from the API
decryptData(key: string, bytesToDecrypt: number[]) {
let ciphertextArray = new CryptoJS.lib.WordArray(bytesToDecrypt);
// Base64 encoded ciphertext, 32 bytes string as key
var keyBytes = CryptoJS.enc.Utf8.parse(key); // Convert into WordArray (using Utf8)
var iv = new CryptoJS.lib.WordArray([0x00, 0x00, 0x00, 0x00]); // Use zero vector as IV
let cipherParams = new CryptoJS.lib.CipherParams({
ciphertext: ciphertextArray,
key: keyBytes,
iv: iv
});
var decryptedBytes = CryptoJS.AES.decrypt(cipherParams, keyBytes, { iv: iv }); // By default: CBC, PKCS7
return decryptedBytes;
}
In the angular app, I call this do decrypt the binary. It returns a WordArray
let decryptedDoc = this.decryptData(key, this.document.file);
I assumed that if I tried converting the number array to a base64 string, I'd have the decrypted binary...
let decryptedBase64 = Buffer.from(decryptedDoc.words).toString('base64');
But the encoded string is corrupt.
Any help on this would be GREATLY appreciated!
Thanks in advance.