ValueError:使用AES256解密时无效的填充字节

时间:2019-08-18 11:54:40

标签: python encryption cryptography aes python-cryptography

我正在尝试使用cryptography库重写this解决方案,但是在解密过程中出现填充错误,即ValueError: Invalid padding bytes.,这是到目前为止我拥有的密码类:

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)

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

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

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

1 个答案:

答案 0 :(得分:2)

您的解密方法是提取密码的前16个字节作为IV,但是您的加密方法从来没有把它放在那。解决方法是让encrypt将IV放在密文之前,然后进行base64编码。

return base64.b64encode(iv + ciphertext)

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

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