在Python和Node之间使用AES加密时出现的问题

时间:2014-04-24 11:37:59

标签: python node.js cryptography aes node-crypto

我想用python(aes-128-ecb)加密字符串,并用节点解密字符串。以下是我写的内容。我不知道为什么它不起作用。

PyCrypto lib doc:http://pythonhosted.org//pycrypto/

节点加密lib doc:http://nodejs.org/api/crypto.html

Python代码

from Crypto.Cipher import AES
import binascii

aes_key = '\x26\x33\x3B\x48\x28\x69\x77\x8C\x14\xA2\xBE\xC1\xD4\xE2\xFD\x14'
aes = AES.new(aes_key)
data = aes.encrypt('testtesttesttest')

print binascii.hexlify(bytearray(data))
# output >> 5cc4711e67703657f0a04d887d7c074e

JS代码

var crypto = require('crypto');

var aes_key = new Buffer('26333B482869778C14A2BEC1D4E2FD14', 'hex');
var data = new Buffer('b4364ee66c808b3b0f24070879a3b224', 'hex');

var aes = crypto.createDecipher('aes-128-ecb', aes_key);
aes.setAutoPadding(false);
var data = Buffer.concat([aes.update(data), aes.final()]);
console.log(data.toString());
// output >> X4b�1�5(��̣F<�f

1 个答案:

答案 0 :(得分:2)

问题是createDecipher()接受密码,而不是密钥。您需要使用createDecipheriv()并为iv参数传递任何Buffer,因为它在ecb模式下被忽略:

var DUMMY_IV = new Buffer(0),
    aes_key = new Buffer('26333B482869778C14A2BEC1D4E2FD14', 'hex'),
    aes = crypto.createDecipheriv('aes-128-ecb', aes_key, DUMMY_IV);
aes.setAutoPadding(false);
var data = Buffer.concat([
  aes.update('5cc4711e67703657f0a04d887d7c074e', 'hex'),
  aes.final()
]);
console.log(data.toString());
// outputs: testtesttesttest