V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
xianlin
V2EX  ›  问与答

使用 Node.js 和 bash script 给字串 AES 加密得到相同的结果

  •  
  •   xianlin · 2016-09-15 12:06:59 +08:00 · 1867 次点击
    这是一个创建于 2788 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我有 2 个 scripts,一个是 node.js,另外一个是 bash.sh

    node.js

    // Nodejs encryption with CTR
    var crypto = require('crypto'),
        algorithm = 'aes-256-ctr',
        password = 'my_password';
    
    function encrypt(text){
      var cipher = crypto.createCipher(algorithm,password)
      var crypted = cipher.update(text, 'utf8', 'hex')
      crypted += cipher.final('hex');
      return crypted;
    }
    
    function decrypt(text){
      var decipher = crypto.createDecipher(algorithm,password)
      var dec = decipher.update(text,'hex','utf8')
      dec += decipher.final('utf8');
      return dec;
    }
    
    var hw = encrypt("14:3b:62:6c:b5:44")
    console.log(hw);
    console.log(decrypt(hw));
    

    bash script

    #!/bin/bash
    #
    
    echo -n "14:3b:62:6c:b5:44" |\
    openssl enc -a -e -aes-256-ctr -nosalt -pass pass:my_password |\
    xxd -p
    

    但这 2 个程序得到了不同的结果

    $ node node_script.js 
    ecb091d31243c56f41acc18bcdab1523c7
    14:3b:62:6c:b5:44
    
    $ ./bash_script.sh 
    374c435230784a4478573942724d474c7a6173564938633d0a
    

    我哪里做错了呢?谢谢

    第 1 条附言  ·  2016-09-15 13:02:33 +08:00
    所以最后结果就是我的 bash script 应该改为:

    ```
    #!/bin/bash
    #

    encryptedStr=$(echo -n "14:3b:62:6c:b5:44" |\
    openssl enc -a -e -aes-256-ctr -nosalt -pass pass:my_password |\
    base64 -d | xxd -p)

    echo $encryptedStr

    decryptedStr=$(echo -n $encryptedStr | xxd -r -p | base64 |\
    openssl enc -a -d -aes-256-ctr -nosalt -pass pass:my_password)

    echo $decryptedStr
    ```
    4 条回复    2016-09-16 00:34:07 +08:00
    ss098
        1
    ss098  
       2016-09-15 12:25:59 +08:00 via Android
    我没记错的话 ... 我之前做的 aes 同样的内容会有不同的结果,你这样应该是没问题的,比对解密后的结果才行。
    xianlin
        2
    xianlin  
    OP
       2016-09-15 12:41:10 +08:00
    @ss098 ,我试过了,把下面 bash 的结果放到 nodejs 的`console.log(decrypt(hw))`里面跑了一次,解密的结果不一样。
    xianlin
        3
    xianlin  
    OP
       2016-09-15 12:57:58 +08:00
    搞定了,中间步骤差了个 base64 的解码!


    ```
    #!/bin/bash
    #
    echo -n "14:3b:62:6c:b5:44" |\
    openssl enc -a -e -aes-256-ctr -nosalt -pass pass:my_password |\
    base64 -d | xxd -p
    ```
    Arthur2e5
        4
    Arthur2e5  
       2016-09-16 00:34:07 +08:00
    base64 是你自己要求 openssl enc 加的呀,-a 。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2586 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 14:19 · PVG 22:19 · LAX 07:19 · JFK 10:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.