Skip to content

Instantly share code, notes, and snippets.

@youben11
Last active January 5, 2022 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youben11/af177be7eebd790d771e4791f738ef6d to your computer and use it in GitHub Desktop.
Save youben11/af177be7eebd790d771e4791f738ef6d to your computer and use it in GitHub Desktop.
Bsides 2022 Crypto Workshop AES
import os
from Crypto.Cipher import AES
# Can be 16, 24, or 32 bytes
KEY = b"A"*16
############
# ECB mode #
############
aes_ecb = AES.new(KEY, mode=AES.MODE_ECB)
message = b"shellmates{ECB_}"
ciphertext = aes_ecb.encrypt(message * 2)
# Two consecutive same blocks are encrypted to the same value in ECB mode
assert ciphertext[:16] == ciphertext[16:]
decrypted_message = aes_ecb.decrypt(ciphertext)
# Decryption is correct
assert decrypted_message == message * 2
############
# CBC mode #
############
IV = os.urandom(16)
aes_cbc = AES.new(KEY, mode=AES.MODE_CBC, IV=IV)
message = b"shellmates{CBC_}"
ciphertext = aes_cbc.encrypt(message * 2)
# Two consecutive same blocks aren't encrypted to the same value in CBC mode
assert ciphertext[:16] != ciphertext[16:]
aes_cbc = AES.new(KEY, mode=AES.MODE_CBC, IV=IV)
decrypted_message = aes_cbc.decrypt(ciphertext)
# Decryption is correct
assert decrypted_message == message * 2
# Now go and learn about CTR and see what wrong with the code below
############
# CTR mode #
############
IV = os.urandom(16)
aes_ctr = AES.new(KEY, mode=AES.MODE_CTR, IV=IV, counter=lambda: b"0"*16)
message = b"shellmates{CTR_}"
secret_message = b"*"*16
ciphertext = aes_ctr.encrypt(message + secret_message)
# Can you recover the secret message without using the key?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment