I created this method to encryped string with a key:
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;
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);
}
But I also need this method in JS, to also decrypt the same string.
I am wondering about
AES, Encoding.UTF8.GetBytes, ICryptoTransform, Cryptostreammode, and MemoryStream.
Do these exist in JS?
IS this method even usable in JS?
Using your C# code to encrypt a string via public static string EncryptString(string key, string plainText) I get following result:
EncryptString("xxxxxxxxxxxxxxxx", "Hello World") -> "yM377gXxX5Du71hgkPH+Fg=="
To reverse this you can check out this Javascript code:
const key = "xxxxxxxxxxxxxxxx";
const msg = "yM377gXxX5Du71hgkPH+Fg==";
const decrypted = CryptoJS.AES.decrypt(
msg,
CryptoJS.enc.Utf8.parse(key),
{ mode: CryptoJS.mode.ECB }
);
console.log(decrypted.toString(CryptoJS.enc.Utf8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>