-
Notifications
You must be signed in to change notification settings - Fork 0
/
p59.py
46 lines (38 loc) · 1.07 KB
/
p59.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import itertools
def char_table():
chars = []
for c in range(128):
good = False
if 32 <= c < 127:
good = True
chars.append(good)
return chars
def guess_keys(cipher):
table = char_table()
src = tuple(range(97, 123))
step = 3
for key in itertools.product(src, repeat=step):
good = True
for i, c in enumerate(cipher):
k = key[i % len(key)]
if not table[k ^ c]:
#print('Failing after {} tries because {}'.format(i, k ^ c))
good = False
break
if good:
yield key
def apply_key(cipher, key):
chars = []
s = 0
for i, c in enumerate(cipher):
k = key[i % len(key)]
chars.append(chr(k ^ c))
s += k ^ c
return s, ''.join(chars)
if __name__ == '__main__':
cipher = []
with open('p059_cipher.txt', mode='r') as f:
for line in f.readlines():
cipher.extend(int(i) for i in line.split(','))
for pwd in guess_keys(cipher):
print(pwd, apply_key(cipher, pwd))