The below AES algorithm in C# returns an encrypted value that is different from what node js and CryptoJS returns. NodeJS Crypto library and CryptoJS return the same values but .NET's AesCryptoServiceProvider returns a different value. Any ideas?

C# example

    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 example:

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 example:

<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>
有帮助吗?

解决方案

Your C# version uses UTF-16LE to convert HelloWorld to plaintext bytes. The NodeJS one (and presumably hence the CryptoJS one) use UTF-8 bytes. Use Encoding.UTF8.GetBytes() in the C# one.

其他提示

Default padding in NodeJS is PKCS5 (assuming CryptoJS is the same since you said they produce the same result). Your C# code is setting padding to PKCS7.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top