+/Cryptopals

git clone https://git.julia.blue/+/Cryptopals

Joseph RyanAdd rust solutions6d42c13

master
1.1 KiB47 linesraw
1from Crypto.Cipher import AES
2from Crypto.Util.Padding import pad
3import random
4
5encryptECB = lambda s, k: AES.new(k, AES.MODE_ECB).encrypt(s)
6
7fixedXor = lambda a, b: bytes([a[i] ^ b[i] for i in range(len(a))])
8
9
10def encryptCBC(s, k, iv):
11    s = pad(s, 16)
12    cipher = [iv]
13    plain = [s[i : i + 16] for i in range(0, len(s), 16)]
14    for p in plain:
15        cipher.append(encryptECB(fixedXor(p, cipher[-1]), k))
16    result = []
17    for i in cipher[1:]:
18        result += i
19    return result
20
21
22def detectCipher(s):
23    temp = [s[i : i + 16] for i in range(0, len(s), 16)]
24    for i in temp:
25        if temp.count(i) > 1:
26            return "ECB"
27    return "CBC"
28
29
30key = random.randbytes(16)
31data = b"this is a test to see how well encryption works" * 20
32enc = ""
33
34data = (
35    random.randbytes(random.randint(5, 10))
36    + data
37    + random.randbytes(random.randint(5, 10))
38)
39
40if random.random() < 0.5:
41    enc = encryptECB(pad(data, 16), key)
42    print("Actual: ECB")
43else:
44    enc = encryptCBC(data, key, random.randbytes(16))
45    print("Actual: CBC")
46
47print("Guess:", detectCipher(enc))