AES加密抛出ValueError:输入字符串长度必须是16的倍数



我想使用AES加密数据,但我得到了ValueError如下:

Traceback (most recent call last):
File "/home/a/AES/aes.py", line 14, in <module>
msg =cipher.encrypt(plaintext)
File "/home/a/anaconda3/envs/AES/lib/python3.9/site-packages/Crypto/Cipher/blockalgo.py", line 244, in encrypt
return self._cipher.encrypt(plaintext)
ValueError: Input strings must be a multiple of 16 in length

代码:

from Crypto.Cipher import AES
key = 'qwertyui87654388'
plaintext = "vgfcomo#456"
cipher = AES.new(key, AES.MODE_ECB)
msg =cipher.encrypt(plaintext)
print(msg.hex())

我想在代码中实现以下项目:

aes。KeySize = 128;

aes。

aes。Mode = CipherMode.ECB;//不合规的

aes。

谁能提出一个解决方案来解决这个问题,并在python代码中实现padding,BlockSizeKeySize?

根据定义,AES的块大小为16字节。允许的密钥大小为16、24和32字节。使用PyCryptodome,这些都不需要设置。密钥大小隐式地与密钥一起设置,其长度必须具有AES允许的值之一。
与许多其他库不同,PyCryptodome默认不应用填充,这是导致错误消息的原因。然而,PyCryptodome支持使用专用模块Crypto.Util填充。填充,pkcs# 7是默认值。

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
key = 'qwertyui87654388'
plaintext = "vgfcomo#456"
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg =cipher.encrypt(pad(plaintext.encode('utf8'), 16))
print(msg.hex()) # 65e44255a2564a4861fcf65801dd6af7

请注意,ECB是一个不安全的模式。


编辑-关于你评论中的问题,解密是用:

from Crypto.Util.Padding import unpad
...
plaintext = unpad(cipher.decrypt(msg), 16) 
...

最新更新