I want to encrypt data using AES
.But I got a ValueError
like below:
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
Code:
from Crypto.Cipher import AES
key = 'qwertyui87654388'
plaintext = "vgfcomo#456"
cipher = AES.new(key, AES.MODE_ECB)
msg =cipher.encrypt(plaintext)
print(msg.hex())
I want to implement below items in the code :
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Mode = CipherMode.ECB; // Noncompliant
aes.Padding = PaddingMode.PKCS7;
Can anyone suggest a solution to solve the issue and implement padding
, BlockSize
and KeySize
in the python code?
CodePudding user response:
AES has by definition a blocksize of 16 bytes. Allowed keysizes are 16, 24 and 32 bytes. With PyCryptodome, none of these need to be set. The keysize is implicitly set with the key, whose length must have one of the values allowed for AES.
Unlike many other libraries, PyCryptodome does not apply padding by default, which is the cause of the error message. However, PyCryptodome supports padding with a dedicated module, Crypto.Util.Padding, where PKCS#7 is the default.
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
Note that ECB is an insecure mode.
Edit - Regarding the question in your comment, decryption is done with:
from Crypto.Util.Padding import unpad
...
plaintext = unpad(cipher.decrypt(msg), 16)
...