我试图用Node.js中的pkcs7填充解密消息没有成功。此消息已加密并从Python代码发送。我设法使其能够在纯Python中工作,但无法弄清楚如何在Node.js中实现解码(pkcs7填充)功能。有人可以帮助我重现代码吗?
Python编码-加密
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==
另外,我将用于pkcs7填充的自定义代码放入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解密
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);
这是错误:
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)
最佳答案
用key = m.hexdigest()
替换key = m.digest()
应该可以解决您的问题。