Search code examples
python-3.xencryptionaespycryptodome

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 lines, but it did not help:

encrypted = encrypt(message)
decrypted = decrypt(encrypted)

I have 2 examples:

Example1

from Crypto.Cipher import AES

key = 'ACD310AE179CE245624BB238867CE189'
message = 'this is my super secret message'

cipher = AES.new(key.encode('utf-8'),AES.MODE_CBC)

def pad(s):
    return s + ((16 - len(s) % 16) * '{')

def encrypt(plaintext):
    global cipher
    return cipher.encrypt(pad(plaintext).encode('utf-8'))

def decrypt(ciphertext):
    global cipher
    dec = cipher.decrypt(ciphertext).decode('utf-8')
    l = dec.count('{')
    return dec[:len(dec)-1]

encrypted = encrypt(message)
decrypted = decrypt(encrypted)

print("Message: ", message)
print("Encrypted: ", encrypted)
print("Decrypted: ", decrypted)

Example 2

from Crypto.Cipher import AES

key = b'Sixteen byte key'
data = b'hello from other side'
cipher = AES.new(key, AES.MODE_EAX)

e_data = cipher.encrypt(data)

d_data = cipher.decrypt(e_data)

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

Solution

  • 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'