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

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

  • 相关阅读:
    开启safe_mode之后对php系统函数的影响
    解析posix与perl标准的正则表达式区别
    教你在不使用框架的情况下也能写出现代化 PHP 代码
    杭州逆行崩溃小伙首度回应
    PHP命令行脚本接收传入参数的三种方式
    PHP魔术方法使用总结
    Nginx服务器的rewrite、全局变量、重定向和防盗链相关功能
    重定向
    P2141 珠心算测验
    T2695 桶哥的问题——吃桶
  • 原文地址:https://www.cnblogs.com/cava/p/3574860.html
Copyright © 2011-2022 走看看