2014-04-24 82 views
0

我想用python(aes-128-ecb)加密一個字符串,並用節點解密字符串。以下是我寫的。我不知道爲什麼它不起作用。在Python和Node之間使用AES加密時的問題

的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 
+0

什麼問題是什麼呢? – majidarif

+0

@majidarif JS代碼的最後一行應該輸出解密的字符串「testtesttesttest」,但它不會 –

回答

2

的問題是,createDecipher()接受密碼,不是鑰匙。您需要使用createDecipheriv()和傳遞任何緩衝的IV參數,因爲它是爲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