Skip to content

Instantly share code, notes, and snippets.

@xct

xct/2aes.py Secret

Created December 28, 2019 08:09
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 xct/59522d8865150aecb2a36a78456b8d6b to your computer and use it in GitHub Desktop.
Save xct/59522d8865150aecb2a36a78456b8d6b to your computer and use it in GitHub Desktop.
2AES meet in the middle attack
#!/usr/bin/env python
import base64
from Cryptodome.Cipher import AES
import hashlib
from Cryptodome.Random import get_random_bytes
import string
from tqdm import tqdm
import base64
test = b'Double AES encryption for twice the strength.Win'
encrypted_test = '0mu0T97looX5/Oorw8ASGxfqMqrNoFajZupXrjtIAj7ECJdQXZzEmbEwdRV2J2MI'
flag = 'lIZMVkA+pbiOxh3nNdV2bWz3gXovIy4fG7yCHa5FT44='
encrypted_test = base64.b64decode(encrypted_test)
flag = base64.b64decode(flag)
iv = hashlib.md5(b"infernoCTF").digest()
alphabet = string.printable
key_base = '0'*29
# decrypting
phase1 = {}
data = encrypted_test
for a in tqdm(string.printable):
for b in string.printable:
for c in string.printable:
key = key_base+a+b+c
key = key.encode()
cipher_decrypt = AES.new(key, AES.MODE_CBC, iv=iv)
ciphertext = cipher_decrypt.decrypt(data)
phase1[key] = ciphertext
print('P1 done')
# encrypting
phase2 = {}
data = test
for a in tqdm(string.printable):
for b in string.printable:
for c in string.printable:
key = key_base+a+b+c
key = key.encode()
cipher_encrypt = AES.new(key, AES.MODE_CBC, iv=iv)
ciphertext = cipher_encrypt.encrypt(data)
phase2[key] = ciphertext
print('P2 done')
s1 = set(phase1.values())
s2 = set(phase2.values())
s3 = s1 & s2
match = s3.pop()
for k,v in phase1.items():
if v == match:
key1 = k
print(f'Key1: {key1}')
for k,v in phase2.items():
if v == match:
key2 = k
print(f'Key2: {key2}')
# decrypt flag
data = flag
cipher_decrypt = AES.new(key1, AES.MODE_CBC, iv=iv)
ciphertext = cipher_decrypt.decrypt(data)
cipher_decrypt = AES.new(key2, AES.MODE_CBC, iv=iv)
ciphertext = cipher_decrypt.decrypt(ciphertext)
print(ciphertext.decode('utf-8'))
# infernoCTF{M33t_in_Th£_M1ddL3!}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment