-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP59.py
66 lines (50 loc) · 1.45 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def combination(string, n):
result = []
m = len(string)
if m - n < n:
n = m - n
if n < 0:
return None
elif n == 0:
return string
elif n == 1:
return [char for char in string]
else:
for i in range(len(string)):
remain = string[:i] + string[i + 1:]
letter = string[i]
result += list(map(lambda x: letter + x,
combination(remain, n - 1)))
return set(result)
def XOR_decryption(message, key):
return [message[i] ^ ord(key[i % 3]) for i in range(len(message))]
def get_text(message):
text = ''
for char in map(chr, message):
text += char
return text
def test_valid(message, word_list):
text = get_text(message)
# words=text.lower().strip('!,.?').split(' ')
count = 0
for word in word_list:
if word in text:
count += 1
return count
with open('p059_cipher.txt') as f:
message = [int(char) for char in f.read().strip().split(',')]
with open('word_list.txt') as f:
word_list = [i[:-1] for i in f.readlines()]
string = ''
for i in range(97, 123):
string += chr(i)
key_set = combination(string, 3)
flag = 0
for key in key_set:
decrypted = XOR_decryption(message, key)
valid_num = test_valid(decrypted, word_list)
if valid_num > flag:
best = decrypted
flag = valid_num
print(get_text(best))
print('\nThe answer is {0}'.format(sum(best)))