简体   繁体   English

C# 中的加密和 javascript 中使用 AES 算法的解密

[英]Encryption in C# and Decryption in javascript with AES Algorithm

I am trying to decrypt the string in JavaScript which is encrypted by using AES 256 algorithm in a C# application.我正在尝试解密 JavaScript 中的字符串,该字符串是在 C# 应用程序中使用 AES 256 算法加密的。 The code of encryption and decryption is as below I am able to decrypt the string in a C# application.加密和解密代码如下 我可以在 C# 应用程序中解密字符串。 I used the below code to decrypt the string JavaScript but I am not able to decrypt我使用以下代码解密字符串 JavaScript 但我无法解密

public string Encrypt(string content)
    {
        if (string.IsNullOrEmpty(content))
        {
            throw new ArgumentNullException("content");
        }

        byte[] encryptedData = null;

        try
        {

            using (AesCryptoServiceProvider aesMod = new AesCryptoServiceProvider())
            {
                //Set the key manullay to predefined values
                aesMod.Key = m_Key;
                aesMod.IV = m_IV;


                ICryptoTransform encryptor = aesMod.CreateEncryptor(aesMod.Key, aesMod.IV);

                // Create the streams used for encryption.
                using (MemoryStream memstreamEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(memstreamEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Writing data to the stream.
                            swEncrypt.Write(content);
                        }
                        encryptedData = memstreamEncrypt.ToArray();
                    }
                }
            }
            return Convert.ToBase64String(encryptedData);
        }
        catch (Exception ex)
        {
            throw new Exception("Exception in Encrypting .", ex);
        }
    }



<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
                <script>

                      function decryptMessage(encryptedMessage = '', secretkey = ''){

                            var cipherParams = CryptoJS.lib.CipherParams.create({
                                ciphertext: CryptoJS.enc.Base64.parse(encryptedMessage)
                            });

                            var decrypted = CryptoJS.AES.decrypt(cipherParams, secretkey);
                            var decryptedMessage = decrypted.toString(CryptoJS.enc.Utf8);

                            return decryptedMessage;


                }
 </script>

The problem could be that the strings in C# are encoded in UTF-16 Try to change the encoding in the JavaScript code, if possible.问题可能是 C# 中的字符串以UTF-16编码 如果可能,尝试更改 JavaScript 代码中的编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM