使用 PKCS7Padding 在 python 和 Node.js 之间进行 AES 加密

Pan*_*tos 0 javascript python encryption cryptography node.js

我正在尝试在 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==
Run Code Online (Sandbox Code Playgroud)

另外,我在 Python pkcs7.py 中放置了 pkcs7 padding 的自定义代码

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())
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

这是错误:

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)
Run Code Online (Sandbox Code Playgroud)