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(''));

  對比發現,加密出來是一致的。好吧,結貼~~~我恨你,浪費了我一天時間。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM