fra*_*ntb 0 python openssl aes node.js
python 中的以下程序:
from Crypto.Cipher import AES
key = '11223344556677889900aabbccddeeff'.decode("hex")
aesECB = AES.new(key, AES.MODE_ECB)
ciphertext = aesECB.encrypt('1234567890abcdef')
print ciphertext.encode('base64')
Run Code Online (Sandbox Code Playgroud)
给我这个结果:
$ python example_cipher.py
r9yD3EmmAIpxncxZSldsKg==
Run Code Online (Sandbox Code Playgroud)
从 openssl 执行命令行后,得到相同的结果:
$ echo -n "1234567890abcdef" | openssl aes-128-ecb -K 11223344556677889900aabbccddeeff -nopad | openssl base64
r9yD3EmmAIpxncxZSldsKg==
Run Code Online (Sandbox Code Playgroud)
但是 Node 中的这段代码:
var crypto = require('crypto');
var key = new Buffer('11223344556677889900aabbccddeeff', 'hex');
var plaintext = new Buffer('1234567890abcdef', 'utf8');
var cipher = crypto.createCipher("aes-128-ecb", key);
cipher.setAutoPadding(false);
var ciphertext = cipher.update(plaintext, 'utf8');
console.log(ciphertext.toString('base64'));
Run Code Online (Sandbox Code Playgroud)
g 没有给我同样的结果:
$ node cipher
tOunZRvle8B6HYuBSzblqw==
Run Code Online (Sandbox Code Playgroud)
错误在哪里?
首先,如果您可以控制加密参数,请勿使用 ECB。它非常不安全,不应该用于加密数据。
现在对于 ECB,技术上不使用 IV,您仍然需要使用crypto.createCipheriv()零长度 IVBuffer来匹配 Python 的输出:
var cipher = crypto.createCipheriv("aes-128-ecb", key, Buffer.alloc(0));
Run Code Online (Sandbox Code Playgroud)
另外(一般来说),您缺少cipher.final()包含任何剩余数据,因此请改用:
var ciphertext = Buffer.concat([
cipher.update(plaintext, 'utf8'),
cipher.final()
]);
Run Code Online (Sandbox Code Playgroud)