python - 值错误: Invalid padding bytes when decrypting with AES256

标签 python encryption cryptography aes python-cryptography

我正在尝试重写this使用cryptography库的解决方案,但在解密过程中我得到填充错误,即ValueError:无效的填充字节。这是我到目前为止的密码类:

import os
import base64

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

class AES256Cipher:

    def __init__(self, password, salt):
        self.password = password.encode('utf-8')
        self.salt = salt.encode('utf-8')

        self.backend = default_backend()
        self.key = self.pbkdf2()

    def encrypt(self, plaintext):
        iv = os.urandom(16)
        cipher = Cipher(
            algorithms.AES(self.key),
            modes.CBC(iv),
            backend=self.backend
        )

        encryptor = cipher.encryptor()
        padder = padding.PKCS7(256).padder()
        plaintext = plaintext.rstrip().encode('utf-8')
        padded = padder.update(plaintext) + padder.finalize()
        ciphertext = encryptor.update(padded) + encryptor.finalize()
        return base64.b64encode(ciphertext)

    def decrypt(self, ciphertext):
        ciphertext = base64.b64decode(ciphertext.rstrip())
        iv = ciphertext[:16]
        cipher = Cipher(
            algorithms.AES(self.key),
            modes.CBC(iv),
            backend=self.backend
        )

        decryptor = cipher.decryptor()
        unpadder = padding.PKCS7(256).unpadder()
        plaintext = decryptor.update(ciphertext) + decryptor.finalize()
        unpadded = unpadder.update(plaintext) + unpadder.finalize()
        return unpadded.decode('utf-8')

    def pbkdf2(self):
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32, salt=self.salt,
            iterations=100000,
            backend=self.backend
        )
        return kdf.derive(self.password)

当代码到达 decrypt 方法中的 unpadded = unpadder.update(plaintext) + unpadder.finalize() 时,会引发异常。为什么填充失败?例如:

password = 'dummy_password'
salt = 'IU^7862390rZI)&(*hi23q2rfbnO(*^$%#'
cipher = AES256Cipher(password, salt)

ct = cipher.encrypt('secret_string')
cipher.decrypt(ct)  # <-- ValueError: Invalid padding bytes.

最佳答案

您的解密方法正在提取密码的前 16 个字节作为 IV,但您的加密方法从未将其放在那里。解决方法是在对密文进行 Base64 编码之前加密将 IV 放在密文前面。

return base64.b64encode(iv + ciphertext)

在解密方面,您必须正确删除它:

iv, ciphertext = ciphertext[:16], ciphertext[16:]

关于python - 值错误: Invalid padding bytes when decrypting with AES256,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544299/

相关文章:

python - Windows VS 中的 Boost numpy 链接器错误

c# - 如果我使用 HMACSha1 作为哈希算法,为什么 PasswordDeriveBytes 每次都会生成不同的 key ?

java - 使用 Java 创建 Node.js 加密 key

encryption - TLS over TLS 可能吗?

python - 如何使用 Python 按值搜索嵌套的 JSON

python - 从 pandas DataFrame 返回最后一个有效(非空)值

python - 我可以在 Python 中搜索一段字符串但保持索引相对于原始字符串吗?

java - 加密应用程序数据的正确方法

asp.net - C# ASP.NET Core 2 中的安全网络聊天

security - 如何保护 webhook 身份