PyCriptodome AES ValueError(“PKCS#7填充不正确。”)

时间:2018-04-28 21:32:36

标签: python cryptography aes

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加密/解密包装器。它适用于以下示例键:

  

key = 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填充不正确。

为什么它会返回此信息,并使用示例键?

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题:如果您的密钥不匹配,则会收到此错误消息。