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

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

  • 相关阅读:
    leetCode 42.Trapping Rain Water(凹槽的雨水) 解题思路和方法
    FizzBuzz and Fibonacci优化
    mysql 存储过程 演示样例代码
    《深入理解Android 卷III》第二章 深入理解Java Binder和MessageQueue
    jsp中URL传递中文參数的处理
    键盘录入多名学生的信息: 格式:姓名,数学成绩,语文成绩,英文成绩,按总分由高到低 将学生的信息进行排列到文件里
    iOS_block代码块
    自己动手写android图片异步载入库
    三分钟教你学Git(十三)
    文本文件打印类库(C#)
  • 原文地址:https://www.cnblogs.com/cava/p/3574860.html
Copyright © 2020-2023  润新知