Reputation: 3224
I am trying with no success to decrypt a message with pkcs7 padding in Node.js. This message was encrypted and sent from Python code. I managed make it work in pure Python but can't figure out how to implement the decode (pkcs7 padding) functionality 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()
m.update(pw_bytes)
key = m.hexdigest()
cipher = AES.new(key, AES.MODE_ECB)
pad_text = pkcs7.encode(text_bytes)
msg = cipher.encrypt(pad_text)
EncodeMsg = base64.b64encode(msg)
encryptedstring = EncodeMsg.decode("utf-8")
print(encryptedstring)
# Output: SxQE+SERkAzYcdG/ESAhiQ==
In addition, I put custom code for pkcs7 padding in Python pkcs7.py
import binascii
try:
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 += decipher.final('utf8');
console.log(decrypted);
This is the error:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Error (native)
at Decipher.Cipher.final (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)
Upvotes: 0
Views: 2342
Reputation: 1532
Replacing key = m.hexdigest()
with key = m.digest()
should solve your problem.
Upvotes: 5