2

我正在尝试使用库重写cryptography解决方案,但在解密过程中出现填充错误,即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.
4

1 回答 1

3

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

return base64.b64encode(iv + ciphertext)

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

iv, ciphertext = ciphertext[:16], ciphertext[16:]
于 2019-08-18T13:06:41.580 回答