Nodejs AES加密

这几天被一个问题困扰着。

Nodejs的AES加密和Java,C#加密出来的不一致。当然,这样就不能解密了。

纠结了许久:后来还是实在不行了,看了下源代码,要不然还得继续纠结下去。

网上说,通常的nodejs AES和其他语言实现不一样。好吧~~或许吧。

 

nodejs的crypto模块。

 var crypto = require('crypto');

    var data = "156156165152165156156";
    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-ecb';
    var key = '78541561566';
    var clearEncoding = 'utf8';
    //var cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    var cipherEncoding = 'base64';
/*加密*/ var cipher = crypto.createCipher(algorithm, key); var cipherChunks = []; cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding)); cipherChunks.push(cipher.final(cipherEncoding)); console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join('')); /*解密*/ var decipher = crypto.createDecipher(algorithm, key); var plainChunks = []; for (var i = 0;i < cipherChunks.length;i++) { plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding)); } plainChunks.push(decipher.final(clearEncoding)); console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));

 的确,没错~~加密解密成功。但是和java,C#中加密出来的不一样啊。神啊。

我想,大家都在这里纠结着吧~~对不对。其实只要加个向量,就可以和一致了。网上搜索出来的资源太少。才让自己纠结那么久。好吧,正确代码是:

 var crypto = require('crypto');

    var data = "156156165152165156156";
    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-ecb';
    var key = '78541561566';
    var clearEncoding = 'utf8';
    var iv = "";
    //var cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    var cipherEncoding = 'base64';
    var cipher = crypto.createCipheriv(algorithm, key,iv);

    var cipherChunks = [];
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));

    var decipher = crypto.createDecipheriv(algorithm, key,iv);
    var plainChunks = [];
    for (var i = 0;i < cipherChunks.length;i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));

    }
    plainChunks.push(decipher.final(clearEncoding));
    console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));

  对比发现,加密出来是一致的。好吧,结贴~~~我恨你,浪费了我一天时间。

转载于:https://www.cnblogs.com/cava/p/3574860.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值