Dropped P2l and P3l from language_models
[cipher-training.git] / cipherbreak.py
1 """A set of functions to break the ciphers give in ciphers.py.
2 """
3
4 import string
5 import collections
6 import norms
7 import logging
8 from itertools import starmap
9 from segment import segment
10 from multiprocessing import Pool
11
12 import matplotlib.pyplot as plt
13
14 logger = logging.getLogger(__name__)
15 logger.addHandler(logging.FileHandler('cipher.log'))
16 logger.setLevel(logging.WARNING)
17 #logger.setLevel(logging.INFO)
18 #logger.setLevel(logging.DEBUG)
19
20 from cipher import *
21 from language_models import *
22
23 # To time a run:
24 #
25 # import timeit
26 # c5a = open('2012/5a.ciphertext', 'r').read()
27 # timeit.timeit('keyword_break(c5a)', setup='gc.enable() ; from __main__ import c5a ; from cipher import keyword_break', number=1)
28 # timeit.repeat('keyword_break_mp(c5a, chunksize=500)', setup='gc.enable() ; from __main__ import c5a ; from cipher import keyword_break_mp', repeat=5, number=1)
29
30
31 def frequencies(text):
32 """Count the number of occurrences of each character in text
33
34 >>> sorted(frequencies('abcdefabc').items())
35 [('a', 2), ('b', 2), ('c', 2), ('d', 1), ('e', 1), ('f', 1)]
36 >>> sorted(frequencies('the quick brown fox jumped over the lazy ' \
37 'dog').items()) # doctest: +NORMALIZE_WHITESPACE
38 [(' ', 8), ('a', 1), ('b', 1), ('c', 1), ('d', 2), ('e', 4), ('f', 1),
39 ('g', 1), ('h', 2), ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1),
40 ('n', 1), ('o', 4), ('p', 1), ('q', 1), ('r', 2), ('t', 2), ('u', 2),
41 ('v', 1), ('w', 1), ('x', 1), ('y', 1), ('z', 1)]
42 >>> sorted(frequencies('The Quick BROWN fox jumped! over... the ' \
43 '(9lazy) DOG').items()) # doctest: +NORMALIZE_WHITESPACE
44 [(' ', 8), ('!', 1), ('(', 1), (')', 1), ('.', 3), ('9', 1), ('B', 1),
45 ('D', 1), ('G', 1), ('N', 1), ('O', 2), ('Q', 1), ('R', 1), ('T', 1),
46 ('W', 1), ('a', 1), ('c', 1), ('d', 1), ('e', 4), ('f', 1), ('h', 2),
47 ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1), ('o', 2), ('p', 1),
48 ('r', 1), ('t', 1), ('u', 2), ('v', 1), ('x', 1), ('y', 1), ('z', 1)]
49 >>> sorted(frequencies(sanitise('The Quick BROWN fox jumped! over... '\
50 'the (9lazy) DOG')).items()) # doctest: +NORMALIZE_WHITESPACE
51 [('a', 1), ('b', 1), ('c', 1), ('d', 2), ('e', 4), ('f', 1), ('g', 1),
52 ('h', 2), ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1), ('n', 1),
53 ('o', 4), ('p', 1), ('q', 1), ('r', 2), ('t', 2), ('u', 2), ('v', 1),
54 ('w', 1), ('x', 1), ('y', 1), ('z', 1)]
55 >>> frequencies('abcdefabcdef')['x']
56 0
57 """
58 return collections.Counter(c for c in text)
59
60
61 def caesar_break(message, fitness=Pletters):
62 """Breaks a Caesar cipher using frequency analysis
63
64 >>> caesar_break('ibxcsyorsaqcheyklxivoexlevmrimwxsfiqevvmihrsasrxliwyrh' \
65 'ecjsppsamrkwleppfmergefifvmhixscsymjcsyqeoixlm') # doctest: +ELLIPSIS
66 (4, -130.849989015...)
67 >>> caesar_break('wxwmaxdgheetgwuxztgptedbgznitgwwhpguxyhkxbmhvvtlbhgtee' \
68 'raxlmhiixweblmxgxwmhmaxybkbgztgwztsxwbgmxgmert') # doctest: +ELLIPSIS
69 (19, -128.82410410...)
70 >>> caesar_break('yltbbqnqnzvguvaxurorgenafsbezqvagbnornfgsbevpnaabjurer' \
71 'svaquvzyvxrnznazlybequrvfohgriraabjtbaruraprur') # doctest: +ELLIPSIS
72 (13, -126.25403935...)
73 """
74 sanitised_message = sanitise(message)
75 best_shift = 0
76 best_fit = float('-inf')
77 for shift in range(26):
78 plaintext = caesar_decipher(sanitised_message, shift)
79 fit = fitness(plaintext)
80 logger.debug('Caesar break attempt using key {0} gives fit of {1} '
81 'and decrypt starting: {2}'.format(shift, fit,
82 plaintext[:50]))
83 if fit > best_fit:
84 best_fit = fit
85 best_shift = shift
86 logger.info('Caesar break best fit: key {0} gives fit of {1} and '
87 'decrypt starting: {2}'.format(best_shift, best_fit,
88 caesar_decipher(sanitised_message, best_shift)[:50]))
89 return best_shift, best_fit
90
91 def affine_break(message, fitness=Pletters):
92 """Breaks an affine cipher using frequency analysis
93
94 >>> affine_break('lmyfu bkuusd dyfaxw claol psfaom jfasd snsfg jfaoe ls ' \
95 'omytd jlaxe mh jm bfmibj umis hfsul axubafkjamx. ls kffkxwsd jls ' \
96 'ofgbjmwfkiu olfmxmtmwaokttg jlsx ls kffkxwsd jlsi zg tsxwjl. jlsx ' \
97 'ls umfjsd jlsi zg hfsqysxog. ls dmmdtsd mx jls bats mh bkbsf. ls ' \
98 'bfmctsd kfmyxd jls lyj, mztanamyu xmc jm clm cku tmmeaxw kj lai ' \
99 'kxd clm ckuxj.') # doctest: +ELLIPSIS
100 ((15, 22, True), -340.601181913...)
101 """
102 sanitised_message = sanitise(message)
103 best_multiplier = 0
104 best_adder = 0
105 best_one_based = True
106 best_fit = float("-inf")
107 for one_based in [True, False]:
108 for multiplier in [x for x in range(1, 26, 2) if x != 13]:
109 for adder in range(26):
110 plaintext = affine_decipher(sanitised_message,
111 multiplier, adder, one_based)
112 fit = fitness(plaintext)
113 logger.debug('Affine break attempt using key {0}x+{1} ({2}) '
114 'gives fit of {3} and decrypt starting: {4}'.
115 format(multiplier, adder, one_based, fit,
116 plaintext[:50]))
117 if fit > best_fit:
118 best_fit = fit
119 best_multiplier = multiplier
120 best_adder = adder
121 best_one_based = one_based
122 logger.info('Affine break best fit with key {0}x+{1} ({2}) gives fit of '
123 '{3} and decrypt starting: {4}'.format(
124 best_multiplier, best_adder, best_one_based, best_fit,
125 affine_decipher(sanitised_message, best_multiplier,
126 best_adder, best_one_based)[:50]))
127 return (best_multiplier, best_adder, best_one_based), best_fit
128
129 def keyword_break(message, wordlist=keywords, fitness=Pletters):
130 """Breaks a keyword substitution cipher using a dictionary and
131 frequency analysis.
132
133 >>> keyword_break(keyword_encipher('this is a test message for the ' \
134 'keyword decipherment', 'elephant', KeywordWrapAlphabet.from_last), \
135 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
136 (('elephant', <KeywordWrapAlphabet.from_last: 2>), -52.834575011...)
137 """
138 best_keyword = ''
139 best_wrap_alphabet = True
140 best_fit = float("-inf")
141 for wrap_alphabet in KeywordWrapAlphabet:
142 for keyword in wordlist:
143 plaintext = keyword_decipher(message, keyword, wrap_alphabet)
144 fit = fitness(plaintext)
145 logger.debug('Keyword break attempt using key {0} (wrap={1}) '
146 'gives fit of {2} and decrypt starting: {3}'.format(
147 keyword, wrap_alphabet, fit,
148 sanitise(plaintext)[:50]))
149 if fit > best_fit:
150 best_fit = fit
151 best_keyword = keyword
152 best_wrap_alphabet = wrap_alphabet
153 logger.info('Keyword break best fit with key {0} (wrap={1}) gives fit of '
154 '{2} and decrypt starting: {3}'.format(best_keyword,
155 best_wrap_alphabet, best_fit, sanitise(
156 keyword_decipher(message, best_keyword,
157 best_wrap_alphabet))[:50]))
158 return (best_keyword, best_wrap_alphabet), best_fit
159
160 def keyword_break_mp(message, wordlist=keywords, fitness=Pletters,
161 chunksize=500):
162 """Breaks a keyword substitution cipher using a dictionary and
163 frequency analysis
164
165 >>> keyword_break_mp(keyword_encipher('this is a test message for the ' \
166 'keyword decipherment', 'elephant', KeywordWrapAlphabet.from_last), \
167 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
168 (('elephant', <KeywordWrapAlphabet.from_last: 2>), -52.834575011...)
169 """
170 with Pool() as pool:
171 helper_args = [(message, word, wrap, fitness)
172 for word in wordlist
173 for wrap in KeywordWrapAlphabet]
174 # Gotcha: the helper function here needs to be defined at the top level
175 # (limitation of Pool.starmap)
176 breaks = pool.starmap(keyword_break_worker, helper_args, chunksize)
177 return max(breaks, key=lambda k: k[1])
178
179 def keyword_break_worker(message, keyword, wrap_alphabet, fitness):
180 plaintext = keyword_decipher(message, keyword, wrap_alphabet)
181 fit = fitness(plaintext)
182 logger.debug('Keyword break attempt using key {0} (wrap={1}) gives fit of '
183 '{2} and decrypt starting: {3}'.format(keyword,
184 wrap_alphabet, fit, sanitise(plaintext)[:50]))
185 return (keyword, wrap_alphabet), fit
186
187
188
189 def plot_frequency_histogram(freqs, sort_key=None):
190 x = range(len(freqs.keys()))
191 y = [freqs[l] for l in sorted(freqs.keys(), key=sort_key)]
192 f = plt.figure()
193 ax = f.add_axes([0.1, 0.1, 0.9, 0.9])
194 ax.bar(x, y, align='center')
195 ax.set_xticks(x)
196 ax.set_xticklabels(sorted(freqs.keys(), key=sort_key))
197 f.show()
198
199
200 if __name__ == "__main__":
201 import doctest
202 doctest.testmod()