zoukankan      html  css  js  c++  java
  • 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(''));
    

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

  • 相关阅读:
    第三百三十二节,web爬虫讲解2—Scrapy框架爬虫—Scrapy使用
    trim思考
    国王验毒酒问题
    有人在群里问mysql如何选择性更新部分条件的问题
    有人在群里问 20180222055怎么转20180222-055 这样的问题
    如何下载腾讯视频的视频转为MP4常用格式视频
    天气预报的大雪真的下了
    群友面试的问题 我搞笑的帮忙回答一下
    电台大神打油诗
    ajax简单手写了一个猜拳游戏
  • 原文地址:https://www.cnblogs.com/cava/p/3574860.html
Copyright © 2011-2022 走看看