【问题标题】:PyCriptodome AES ValueError("PKCS#7 padding is incorrect.")PyCriptodome AES ValueError(“PKCS#7 填充不正确。”)
【发布时间】:2018-04-28 21:32:36
【问题描述】:
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 raise ValueError("PKCS#7 padding is wrong.") ValueError: PKCS#7 padding is wrong.

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

【问题讨论】:

  • 我认为问题出在我的密钥生成上。对于 AES,我需要一个固定大小的密钥,我想从一个整数生成一个密钥,但现在我做错了。

标签: python cryptography aes


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2013-09-10
    • 2023-03-17
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多