I recently had to figure out a way to encrypt a string sent from a JavaScript app client and then receive that string on an ASP.NET server and subsequently decrypt it. Below is first the client-side JavaScript code, and then the server-side C# code. The key and iv have to be the same on both client and server and should be concealed from any 3rd party if possible. I’ve used a random string “8056483646328763” as both here, but please change it if you use this code. Make sure the size arguments match the size of your key string, so 128/8 (=16) in this case. This method uses the AES encryption/decryption algorithm, which can be used in javascript as part of the CryptoJS library, which you can download here. For C#, this algorithm is available as part of the security/cryptography standard libraries, but you must put in the relevant using directives above your code. Specifically, here is the javascript:
var key = CryptoJS.enc.Utf8.parse(‘8056483646328763’);
var iv = CryptoJS.enc.Utf8.parse(‘8056483646328763’);
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(stringToEncrypt), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString();`
and here’s the C#:
public string DecryptStringAES(string encryptedValue)
{
var keybytes = Encoding.UTF8.GetBytes(“8056483646328763”);
var iv = Encoding.UTF8.GetBytes(“8056483646328763”);
//DECRYPT FROM CRIPTOJS
var encrypted = Convert.FromBase64String(encryptedValue);
var decryptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);
return decryptedFromJavascript;
}private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
{
throw new ArgumentNullException(“cipherText”);
}if (key == null || key.Length <= 0)
{
throw new ArgumentNullException(“key”);
}if (iv == null || iv.Length <= 0)
{
throw new ArgumentNullException(“key”);
}// Declare the string used to hold
// the decrypted text.string plaintext = null;// Create an RijndaelManaged object
// with the specified key and IV.using (var rijAlg = new RijndaelManaged())
{ //Settings
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.FeedbackSize = 128;
rijAlg.Key = key;
rijAlg.IV = iv; // Create a decrytor to perform the stream transform. var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for decryption. using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{ // Read the decrypted bytes from the decrypting stream
// and place them in a string. plaintext = srDecrypt.ReadToEnd();
}
}
}
}