Question

I want to encrypt a string with python (aes-128-ecb), and decrypt the string with node. Below is what I wrote. I don't know why it doesn't work.

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

The node crypto lib doc: http://nodejs.org/api/crypto.html

Python code

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 code

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
Was it helpful?

Solution

The problem is that createDecipher() accepts a password, not a key. You need to use createDecipheriv() and pass any Buffer for the iv argument since it is ignored for ecb mode:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top