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

2016-09-15 12:06:59 +08:00
 xianlin

我有 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

我哪里做错了呢?谢谢

1916 次点击
所在节点    问与答
4 条回复
ss098
2016-09-15 12:25:59 +08:00
我没记错的话 ... 我之前做的 aes 同样的内容会有不同的结果,你这样应该是没问题的,比对解密后的结果才行。
xianlin
2016-09-15 12:41:10 +08:00
@ss098 ,我试过了,把下面 bash 的结果放到 nodejs 的`console.log(decrypt(hw))`里面跑了一次,解密的结果不一样。
xianlin
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
2016-09-16 00:34:07 +08:00
base64 是你自己要求 openssl enc 加的呀,-a 。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/306419

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX