Nodejs AES加密

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

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

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

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

 

nodejs的crypto模块。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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‘;<br>/*加密*/
    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#中加密出来的不一样啊。神啊。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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(‘‘));

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

Nodejs AES加密,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。