I am facing problems in "Encryption in ASP.net Core and Decryption in Angular". I want to send sensitive information to FE from my BE so I am trying to add encryption and decryption.
My ASP code for encryption is :
public static string EncryptString(string key, string plainText)
{
byte[] iv = new byte[16];
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
{
streamWriter.Write(plainText);
}
array = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(array);
}
And my Angular Code for Decryption is: (Using crypto-js for decryption)
decryptData(data,key) {
try {
const bytes = CryptoJS.AES.decrypt(data, key); //data is encrypted string from ASP
if (bytes.toString()) {
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}
return data;
} catch (e) {
console.log(e);
}
}
After running the code I am getting errors like :
Error: Malformed UTF-8 data at Object.stringify (core.js:513) at WordArray.init.toString (core.js:268) at ...
Thank you.