首页 > 解决方案 > PyCriptodome AES ValueError(“PKCS#7 填充不正确。”)

问题描述

from Crypto.Cipher import AES

import hashlib

def encryptString(plaintext, key):
    # Encryption#
    plaintext = Padding.pad(plaintext, AES.block_size);

    iv = get_random_bytes(AES.block_size)
    print('How many:' , sys.getsizeof(key));
    cipher = AES.new(key, AES.MODE_CBC, iv)

    ciphertext = cipher.encrypt(plaintext);
    return (iv + ciphertext).hex();

def decryptString(ciphertextHex, key):
    ciphertext = binascii.unhexlify(ciphertextHex)
    iv = ciphertext[:AES.block_size]
    ciphertext = ciphertext[AES.block_size:]

    cipher = AES.new(key, AES.MODE_CBC, iv)

    plaintext = cipher.decrypt(ciphertext)
    plaintext = Padding.unpad(plaintext, AES.block_size)

    return plaintext.decode('utf-8');

我创建了一个 AES 加密/解密包装器。它与示例键一起使用,例如:

键 = b'0123456789abcdef0123456789abcdef'

但是,如果我生成这样的随机 AES 密钥(来自字符串)

def convertKey(self,key):
    return hashlib.sha256(key.encode()).digest();

然后它返回此错误:

文件“C:\Python36\lib\site-packages\Crypto\Util\Padding.py”,第 93 行,在 unpad 中引发 ValueError("PKCS#7 填充不正确。") ValueError: PKCS#7 填充不正确。

任何想法为什么它返回这个,并使用示例密钥?

标签: pythoncryptographyaes

解决方案


我设法修复它:如果您的密钥不匹配,您会收到此错误消息。


推荐阅读