NodeJS |加密加密无法产生正确的结果

时间:2017-09-19 10:38:50

标签: node.js encryption cryptography

我有一个棘手的问题需要解决。不确定如何正确解释它,但会尽力而为。所以这就是我想要做的:我正在尝试使用第三方API,它希望我加密一个值并提交它。我使用以下块通过C#代码成功实现了它:

public string Encrypt(byte[] dataToEncrypt, byte[] keyBytes)
       {
           AesManaged tdes = new AesManaged();

           tdes.KeySize = 256;
           tdes.BlockSize = 128;
           tdes.Key = keyBytes;
           tdes.Mode = CipherMode.ECB;
           tdes.Padding = PaddingMode.PKCS7;

           ICryptoTransform crypt = tdes.CreateEncryptor();
           byte[] cipher = crypt.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
           tdes.Clear();
           return Convert.ToBase64String(cipher, 0, cipher.Length);

       }

现在,我正在尝试在Node中实现相同的功能。我写了以下函数。

encrypt(buffer){
            var buffbytes = new Buffer('my app key goes here to be used as password','utf8'); //converts the app key into buffer stream
            return this.encrypt_key(new Buffer(buffer,'utf8'), buffbytes);
        },

        encrypt_key(buffer, keybytes){
            var cipher = crypto.createCipher('aes-128-ecb',keybytes);
            var crypted = cipher.update(buffer,'utf8','base64');
            crypted = crypted+ cipher.final('base64');
            return crypted;
        },

此加密代码正常。它加密很好,但它没有像c#代码那样加密它。当我从C#代码中获取加密文本并将加密结果注入API调用时,它会通过罚款,但是当我将加密结果用于API调用时,它无法提及我的密钥格式不正确。 / p>

我想知道这些代码块是否相同。我假设它是相同的,因为使用128位AES,ECB密码和加密节点模块的默认填充的代码都是PKCS5,它与用于128位加密的PKCS7相同。请帮助!

编辑:9/19/2017

根据@smarx解决方案修复:

        encrypt(buffer){
            var buffbytes = new Buffer(helper.Constants.AppKey,'utf8'); //converts the app key into buffer stream
            return this.encrypt_key(new Buffer(buffer,'utf8'), helper.Constants.AppKey);
        },

        encrypt_key(buffer, key){
            var cipher = crypto.createCipheriv('aes-256-ecb',key,new Buffer(0));
            var crypted = cipher.update(buffer,'utf8','base64');
            crypted = crypted+ cipher.final('base64');
            console.log('printed: ', crypted);
            return crypted;
        },

1 个答案:

答案 0 :(得分:2)

在Node.js代码中,您使用了错误的密码算法。使用aes-256-ecb,因为您使用的是256位密钥。另外,请务必使用createCipheriv,因为createCipher需要密码 it derives an encryption key

单线修复:

const cipher = crypto.createCipheriv('aes-256-ecb', key, new Buffer(0));

以下两个程序产生相同的输出(Q9VZ73VKhW8ZvdcBzm05mw==)。

C#:

var key = System.Text.Encoding.UTF8.GetBytes("abcdefghijklmnopqrstuvwxyz123456");
var data = System.Text.Encoding.UTF8.GetBytes("Hello, World!");

var aes = new AesManaged {
    Key = key,
    Mode = CipherMode.ECB,
};

Console.WriteLine(Convert.ToBase64String(
    aes.CreateEncryptor().TransformFinalBlock(data, 0, data.Length)));

Node.js的:

const crypto = require('crypto');

const key = 'abcdefghijklmnopqrstuvwxyz123456';
const data = 'Hello, World!';

const cipher = crypto.createCipheriv('aes-256-ecb', key, new Buffer(0));
console.log(cipher.update(data, 'utf-8', 'base64') + cipher.final('base64'));