1
I have the following code working perfectly:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
key = b'Sixteen byte key'
data = 'some text to encrypt'.encode("UTF-8")
data = pad(data, AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC)
iv = encryptor.IV
decryptor = AES.new(key, AES.MODE_CBC, IV=iv)
ciphertext = encryptor.encrypt(data)
print(ciphertext)
plaintext = decryptor.decrypt(ciphertext)
print(unpad(plaintext, 16))
But when trying to turn it into a function the result presents padding error. Code adapted to a function:
def cbc(msg, op):
key = b'Sixteen byte key'
encryptor = AES.new(key, AES.MODE_CBC)
iv = encryptor.IV
decryptor = AES.new(key, AES.MODE_CBC, IV=iv)
if op == 1:
data = msg.encode("UTF-8")
data = pad(data, AES.block_size)
ciphertext = encryptor.encrypt(data)
print(ciphertext)
else:
plaintext = decryptor.decrypt(msg)
print(unpad(plaintext, 16))
Error message:
Traceback (most recent call last):
File "D:/Google Drive/max/AES.py", line 48, in <module>
cbc(b'*\xd3\xc1Y\xc2f;\xf0\xc0@\xd9E\xc5x\x11\xb4', 2)
File "D:/Google Drive/max/AES.py", line 19, in cbc
print(unpad(plaintext, 16))
File "C:\Users\Evilmaax\AppData\Local\Programs\Python\Python36\lib\site-packages\Crypto\Util\Padding.py", line 90, in unpad
raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.
The error at the else
, when I pass a byte message *\xd3\xc1Y\xc2f;\xf0\xc0@\xd9E\xc5x\x11\xb4
by parameter. The strange thing is that the message was generated with exactly the same code, with the if
prior to else
in question.
Does anyone have any idea what might be going on?
Using a fixed IR is unsafe! You need to generate a random IR and send it along with the message. Nor should it use only encryption, but authenticated encryption, such as GCM
– Conrado