xXxpRoGrAmmErxXx xXxpRoGrAmmErxXx - 2 years ago 512
Javascript Question

AES encryption between python and Node.js with PKCS7Padding

I am trying with no success decrypt a message with pkcs7 padding in node.js. This message was encrypted and sent from python code. I managed do it work in pure python but i can't do the decode(pkcs7 padding) in node.js. Can anybody help me reproduce the code?

python Encode-Encrypt

import base64
import hashlib
from Crypto.Cipher import AES
import pkcs7

text = "data"
pasword = "key"

pw_bytes = pasword.encode('utf-8')
text_bytes = text.encode('utf-8')

m = hashlib.md5()
key = m.hexdigest()
cipher =, AES.MODE_ECB)
pad_text = pkcs7.encode(text_bytes)
msg = cipher.encrypt(pad_text)
EncodeMsg = base64.b64encode(msg)
encryptedstring = EncodeMsg.decode("utf-8")

# Output: SxQE+SERkAzYcdG/ESAhiQ==

in addition, i put custom code for pkcs7 padding in python

import binascii
from StringIO import StringIO
except ImportError:
from io import StringIO

def decode(bytestring, k=16):
val = binascii.hexlify(bytestring[-1])
val = int(val, 16)
if val > k:
raise ValueError('Input is not padded or padding is corrupt')
l = len(bytestring) - val
return bytestring[:l]

def encode(bytestring, k=16):
l = len(bytestring)
output = StringIO()
val = k - (l % k)
for _ in range(val):
output.write('%02x' % val)
return bytestring + binascii.unhexlify(output.getvalue())

Node.js Decrypt

const crypto = require('crypto');
var decipher = crypto.createDecipher('aes-128-ecb', 'key');
var decrypted = decipher.update('SxQE+SERkAzYcdG/ESAhiQ==', 'base64', utf8');
decrypted +='utf8');


this is the error

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Error (native)
at (crypto.js:153:26)
at Object.<anonymous> (/root/Documents/Testing-Repo/node.js/testing.js:21:23)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Timeout.Module.runMain [as _onTimeout] (module.js:447:10)
at tryOnTimeout (timers.js:224:11)
at Timer.listOnTimeout (timers.js:198:5)

Answer Source

Replacing key = m.hexdigest() with key = m.digest() should solve your problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download