python - 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 填充不正确。
任何想法为什么它返回这个,并使用示例密钥?
解决方案
我设法修复它:如果您的密钥不匹配,您会收到此错误消息。
推荐阅读
- sql - SQL Server Reporting Services:使用 Windows 身份验证
- c - 将消息翻译成 B1FF 语言时出现问题
- ssh - 通过 ssh 进行 cpanel 完整备份,但以 cpanel 用户身份登录
- javascript - 如何让机器人响应频道提及?
- tkinter - Tkinter 串行输入数据
- javascript - Nightwatch .element() 总是使用数组中的最后一个值
- javascript - 如何在嵌套的 for of 循环中进行提取
- mongodb - 在 mongo 聚合调用中添加字典的值
- jakarta-ee - 如何在 Wildfly 的 Qpid 6.1.7 资源适配器中禁用 XA
- python - 使用 selenium,我怎样才能只找到前 N 个元素以更快地运行?