Skip to content

Instantly share code, notes, and snippets.

@ecamellini
Created October 20, 2016 18:08
Show Gist options
  • Save ecamellini/bffb16ba37fbee634ffff1251fca4b3b to your computer and use it in GitHub Desktop.
Save ecamellini/bffb16ba37fbee634ffff1251fca4b3b to your computer and use it in GitHub Desktop.
hack.lu CTF 2016 - cryptolocker
from Crypto.Cipher import AES
import hashlib
import subprocess
def str_to_bytes(data):
u_type = type(b''.decode('utf8'))
if isinstance(data, u_type):
return data.encode('utf8')
return data
def brute(ciphertext, plain):
cn_1 = ciphertext[-32:-16]
cn = ciphertext[-16:]
print("cn_1", cn_1)
print("cn", cn)
return brute_loop(cn, cn_1, plain)
def brute_loop(cn, cn_1, plain):
for i in range(2**8):
for j in range(2**8):
key = bytes([i,j])
hk = hashlib.sha256(key).digest()
cipher = AES.new(hk, AES.MODE_CBC, cn_1)
dec = cipher.decrypt(cn)
if(dec == plain):
print("KEY:", key)
print("Found")
return key
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
def final_brute(iv1, cipertext1):
for i in range(2**8):
for j in range(2**8):
key = bytes([i,j])
hk = hashlib.sha256(key).digest()
cipher = AES.new(hk, AES.MODE_CBC, iv1)
dec = _unpad(cipher.decrypt(ciphertext1[16:]))
open("flag.odt", "wb").write(dec)
try:
print(i, j)
out = subprocess.check_output(['unzip','flag.odt'])
print("Done.")
return key
except:
continue
ciphertext4 = open("flag.encrypted", "rb").read()
pad = str_to_bytes((chr(16))) * 16
key4 = brute(ciphertext4, pad)
iv4 = ciphertext4[:16]
cipher = AES.new(hashlib.sha256(key4).digest(), AES.MODE_CBC, iv4)
ciphertext3 = cipher.decrypt(ciphertext4[16:-16])
open("c3.encrypted", "wb").write(ciphertext3)
key3 = brute(ciphertext3, pad)
iv3 = ciphertext3[:16]
cipher = AES.new(hashlib.sha256(key3).digest(), AES.MODE_CBC, iv3)
ciphertext2 = cipher.decrypt(ciphertext3[16:-16])
open("c2.encrypted", "wb").write(ciphertext2)
key2 = brute(ciphertext2, pad)
iv2 = ciphertext2[:16]
cipher = AES.new(hashlib.sha256(key2).digest(), AES.MODE_CBC, iv2)
ciphertext1 = cipher.decrypt(ciphertext2[16:-16])
open("c1.encrypted", "wb").write(ciphertext1)
iv1 = ciphertext1[:16]
print(key2 + key3 + key4)
# Solution: Sg52WH4D
print(final_brute(iv1, ciphertext1) + key2 + key3 + key4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment