AES

Lesson 32: AES (CBC and EAX mode) using pycryptodome

Note: you should substitute your own desired file to encrypt in place of tux.png

CBC mode encrypt:

#AES CBC mode encryption

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes


with open('tux.png', 'rb') as f:
    data = f.read()

data = pad(data, AES.block_size) #pad to 16 bytes

key = get_random_bytes(16) #using 128bit encryption

#save aes key to aeskey file
with open('aeskey','wb') as f:
    f.write(key)

cipher = AES.new(key, AES.MODE_CBC) #creates iv automatically

e_data = cipher.encrypt(data)


with open('enc_data','wb') as f:
    f.write(cipher.iv) #16 bytes at the top of the file
    f.write(e_data)

CBC mode decrypt:

#AES CBC decryption

from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

with open('enc_data','rb') as f:
    iv = f.read(16)
    e_data= f.read()

with open('aeskey', 'rb') as f:
    key = f.read()

cipher = AES.new(key, AES.MODE_CBC, iv)

data = cipher.decrypt(e_data)
#data = unpad(data, AES.block_size) #reverse order

with open('tux2.png','wb') as f:
    f.write(data)

EAX mode encrypt: Note: EAX incorporates message authentication

#AES encryption (EAX mode: authenticated encryption mode)
#recommended mode

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

key = get_random_bytes(16)

with open('aes_eax_key', 'wb') as f:
    f.write(key)

cipher = AES.new(key, AES.MODE_EAX)

with open('tux.png', 'rb') as f:
    data = f.read()

e_data, tag = cipher.encrypt_and_digest(data)

with open("enc_data.eax", "wb") as f:
    f.write(cipher.nonce)
    f.write(tag)
    f.write(e_data)

EAX mode decrypt:

#AES decryption (EAX mode)

from Crypto.Cipher import AES

with  open('enc_data.eax', 'rb') as f:
    nonce = f.read(16)
    tag = f.read(16)
    e_data = f.read()

with open('aes_eax_key', 'rb') as f:
    key = f.read()

try:
    cipher = AES.new(key, AES.MODE_EAX, nonce)
    data = cipher.decrypt_and_verify(e_data, tag)
except ValueError:
    print('Decryption failed. Encrypted data possibly tampered')

with open('tux3.png','wb') as f:
    f.write(data)