鉴于最后一块未正确填充。如果在解密过程中使用错误的密钥,可能会出现此类问题 - 使用 pycryptodome 进行 AES 加密

问题描述 投票:0回答:1

我使用以下类进行编码和解码,当将加密字符串直接从加密函数传递到解密函数时,它可以正常工作。但是,如果我尝试使用在线解密来解密加密的字符串,则会抛出此错误,并且如果我尝试从外部源解密加密的字符串,也会发生同样的情况。

class AESCipher(object):
    def __init__(self, key):
        self.bs = AES.block_size
        self.key = bytes.fromhex(key)

    def encrypt(self, raw):
        raw = pad(raw.encode('utf-8'), AES.block_size)
        cipher = AES.new(self.key, AES.MODE_ECB)
        encrypted_data = cipher.encrypt(raw)
        return encrypted_data.hex()

    def decrypt(self, enc):
        enc = bytes.fromhex(enc)
        cipher = AES.new(self.key, AES.MODE_ECB)
        decrypted_data = cipher.decrypt(enc)
        return decrypted_data

我尝试使用不同类型的 .hex 以及编码和解码,但结果都相同。

python encryption aes pycrypto pycryptodome
1个回答
0
投票

bytes.fromhex(key)
替换为
bytes(key, "utf-8")
解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.