Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
goelp14
GitHub Repository: goelp14/easyctf-iv-problems
Path: blob/master/aes/aes.py
671 views
1
#!/usr/bin/env python3
2
3
from Crypto import Random
4
from Crypto.Random import random
5
from Crypto.Cipher import AES
6
from binascii import *
7
8
flag = "easyctf{beswymplirxwlhfsoupvqrwdqeabfrkdxgwhdawmvaklvdwxty}"
9
10
BLOCK_SIZE = 16
11
12
# Pad m using PKCS#7
13
def pad(m):
14
p = BLOCK_SIZE - len(m) % BLOCK_SIZE
15
return m + p * bytes([p])
16
17
# AES encrypt
18
def encrypt(key, message, mode=AES.MODE_CBC):
19
IV = key # totally a good idea
20
aes = AES.new(key, mode, IV)
21
return hexlify(IV + aes.encrypt(pad(message))).decode()
22
23
key = Random.get_random_bytes(16)
24
print("The key for this session is: {}".format(key))
25
print("Input 256 different plaintexts such that:")
26
print("\t - Each is a binary string")
27
print("\t - Each has length 256")
28
print("\t - Input can not be all 0's or all 1's")
29
print("\t - Let Pi denote the ith plaintext input. Then P0 ^ P1 ^ ... ^ P255 = encrypt(key, P0) ^ encrypt(key, P1) ^ ... ^ encrypt(key, P255)")
30
31
xor_1 = 0
32
xor_2 = 0
33
34
inputs = set()
35
for _ in range(256):
36
i = input("Input plaintext {}:\t".format(_))
37
38
if i in inputs or len(i) != 256 or not set(i) == set('01'):
39
print("Input error")
40
xor_1 = 0
41
xor_2 = 1
42
break
43
44
inputs.add(i)
45
46
input_dec = int(i, 2)
47
xor_1 ^= input_dec
48
49
t = hex(input_dec).lstrip("0x").rstrip("l")
50
if len(t) & 1:
51
t = unhexlify("0" + t)
52
else:
53
t = unhexlify(t)
54
55
xor_2 ^= int(encrypt(key, t), 16)
56
57
if xor_1 == xor_2:
58
print(flag)
59
else:
60
print("Try again")
61
62
63