Skip to content Skip to sidebar Skip to footer

TypeError: Decrypt() Cannot Be Called After Encrypt()

I am writing a simple code of AES encryption and I got stuck at a part where it says: TypeError: decrypt() cannot be called after encrypt() I tried changing the sequence of these

Solution 1:

The docstring for the decrypt() function does mention:

A cipher object is stateful: once you have decrypted a message
    you cannot decrypt (or encrypt) another message with the same
    object.

So apparently you need to create a new cipher object after encryption to do the decryption. The official documentation has an example which you can leverage. Something like this, which is a minor modification to your example 2:

from Crypto.Cipher import AES

key = b'Sixteen byte key'
data = b'hello from other side'

e_cipher = AES.new(key, AES.MODE_EAX)
e_data = e_cipher.encrypt(data)

d_cipher = AES.new(key, AES.MODE_EAX, e_cipher.nonce)
d_data = d_cipher.decrypt(e_data)

print("Encryption was: ", e_data)
print("Original Message was: ", d_data)

Trying it out:

$ python encdec.py 
Encryption was:  b'P\x06Z:QF\xc3\x9f\x8b\xc9\x83\xe6\xfd\xfa\x99\xfc\x0f\xa0\xc5\x19\xf0'
Original Message was:  b'hello from other side'

Post a Comment for "TypeError: Decrypt() Cannot Be Called After Encrypt()"