I am writing a simple code of AES encryption and I got stuck at a part where it says:
TypeError:
decrypt()
cannot be called afterencrypt()
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)