c# - .NET和nodejs、CryptoJS之间的AES算法值差异

标签 c# node.js encryption aes cryptojs

以下 C# 中的 AES 算法返回的加密值与 Node js 和 CryptoJS 返回的加密值不同。 NodeJS Crypto 库和 CryptoJS 返回相同的值,但 .NET 的 AesCryptoServiceProvider 返回不同的值。有什么想法吗?

C# 示例

    private const string AesIV = @"!QAZ2WSX#EDC4RFV";
    private const string AesKey = @"5TGB&YHN7UJM(IK<";


    public static void Main()
    {
        try
        {
            string original = "HelloWorld";
            Console.WriteLine(Encrypt(original));
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e.Message);
        }
    }
    /// <summary>
    /// AES Encryption
    /// </summary>
    private static string Encrypt(string text)
    {
        // AesCryptoServiceProvider
        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.BlockSize = 128;
        aes.KeySize = 128;
        aes.IV = Encoding.UTF8.GetBytes(AesIV);
        aes.Key = Encoding.UTF8.GetBytes(AesKey);
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        // Convert string to byte array
        byte[] src = Encoding.Unicode.GetBytes(text);

        // encryption
        using (ICryptoTransform encrypt = aes.CreateEncryptor())
        {
            byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

            // Convert byte array to Base64 strings
            return Convert.ToBase64String(dest);
        }
    }

NodeJS 示例:

crypto = require "crypto"
algo = 'aes-128-cbc'
keyBuffer = new Buffer("!QAZ2WSX#EDC4RFV")
ivBuffer = new Buffer("5TGB&YHN7UJM(IK<")

cipher = crypto.createCipheriv(algo, keyBuffer, ivBuffer)
textBuffer = new Buffer('HelloWorld')
encrypted = cipher.update(textBuffer)
encryptedFinal = cipher.final()
encryptedText = encrypted.toString('base64') + encryptedFinal.toString('base64')

console.log encryptedText

CryptoJS 示例:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
    var key = CryptoJS.enc.Utf8.parse('!QAZ2WSX#EDC4RFV');
    var iv  = CryptoJS.enc.Utf8.parse('5TGB&YHN7UJM(IK<');

    var encrypted = CryptoJS.AES.encrypt("HelloWorld", key, { iv: iv });

    alert(encrypted);
</script>

最佳答案

您的 C# 版本使用 UTF-16LE 将 HelloWorld 转换为纯文本字节。 NodeJS(大概也是 CryptoJS)使用 UTF-8 字节。在 C# 中使用 Encoding.UTF8.GetBytes()。

关于c# - .NET和nodejs、CryptoJS之间的AES算法值差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22262033/

相关文章:

c# - 在 DisplayTemplate 中访问模型属性

node.js - 类型错误 : Cannot read property 'passport' of undefined nodejs

encryption - 如何混淆lua代码?

encryption - SHA1 与 RSA : what's the difference between them?

c# - Web API 方法永远不会被路由到

c# - 计算更改操作 c#

javascript - 从 Node.js 生成多个 phantomjs Worker 是否理想?

Python 和最多 21 个字符的随机键

c# - 我以前从未见过的新 MEF 错误 -- "The export is not assignable to type..."

node.js - ArangoDB 插入速度极慢