Merged updated cipherbreak.py from development
[cipher-training.git] / cipherbreak.py
1 import string
2 import collections
3 import norms
4 import logging
5 from itertools import zip_longest, cycle, permutations, starmap
6 from segment import segment
7 from multiprocessing import Pool
8 from math import log10
9
10 import matplotlib.pyplot as plt
11
12 logger = logging.getLogger(__name__)
13 logger.addHandler(logging.FileHandler('cipher.log'))
14 logger.setLevel(logging.WARNING)
15 #logger.setLevel(logging.INFO)
16 #logger.setLevel(logging.DEBUG)
17
18 from cipher import *
19 from language_models import *
20
21 # To time a run:
22 #
23 # import timeit
24 # c5a = open('2012/5a.ciphertext', 'r').read()
25 # timeit.timeit('keyword_break(c5a)', setup='gc.enable() ; from __main__ import c5a ; from cipher import keyword_break', number=1)
26 # 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)
27
28 transpositions = collections.defaultdict(list)
29 for word in keywords:
30 transpositions[transpositions_of(word)] += [word]
31
32 def frequencies(text):
33 """Count the number of occurrences of each character in text
34
35 >>> sorted(frequencies('abcdefabc').items())
36 [('a', 2), ('b', 2), ('c', 2), ('d', 1), ('e', 1), ('f', 1)]
37 >>> sorted(frequencies('the quick brown fox jumped over the lazy ' \
38 'dog').items()) # doctest: +NORMALIZE_WHITESPACE
39 [(' ', 8), ('a', 1), ('b', 1), ('c', 1), ('d', 2), ('e', 4), ('f', 1),
40 ('g', 1), ('h', 2), ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1),
41 ('n', 1), ('o', 4), ('p', 1), ('q', 1), ('r', 2), ('t', 2), ('u', 2),
42 ('v', 1), ('w', 1), ('x', 1), ('y', 1), ('z', 1)]
43 >>> sorted(frequencies('The Quick BROWN fox jumped! over... the ' \
44 '(9lazy) DOG').items()) # doctest: +NORMALIZE_WHITESPACE
45 [(' ', 8), ('!', 1), ('(', 1), (')', 1), ('.', 3), ('9', 1), ('B', 1),
46 ('D', 1), ('G', 1), ('N', 1), ('O', 2), ('Q', 1), ('R', 1), ('T', 1),
47 ('W', 1), ('a', 1), ('c', 1), ('d', 1), ('e', 4), ('f', 1), ('h', 2),
48 ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1), ('o', 2), ('p', 1),
49 ('r', 1), ('t', 1), ('u', 2), ('v', 1), ('x', 1), ('y', 1), ('z', 1)]
50 >>> sorted(frequencies(sanitise('The Quick BROWN fox jumped! over... ' \
51 'the (9lazy) DOG')).items()) # doctest: +NORMALIZE_WHITESPACE
52 [('a', 1), ('b', 1), ('c', 1), ('d', 2), ('e', 4), ('f', 1), ('g', 1),
53 ('h', 2), ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1), ('n', 1),
54 ('o', 4), ('p', 1), ('q', 1), ('r', 2), ('t', 2), ('u', 2), ('v', 1),
55 ('w', 1), ('x', 1), ('y', 1), ('z', 1)]
56 >>> frequencies('abcdefabcdef')['x']
57 0
58 """
59 return collections.Counter(c for c in text)
60
61
62 def caesar_break(message, fitness=Pletters):
63 """Breaks a Caesar cipher using frequency analysis
64
65 >>> caesar_break('ibxcsyorsaqcheyklxivoexlevmrimwxsfiqevvmihrsasrxliwyrh' \
66 'ecjsppsamrkwleppfmergefifvmhixscsymjcsyqeoixlm') # doctest: +ELLIPSIS
67 (4, -130.849989015...)
68 >>> caesar_break('wxwmaxdgheetgwuxztgptedbgznitgwwhpguxyhkxbmhvvtlbhgtee' \
69 'raxlmhiixweblmxgxwmhmaxybkbgztgwztsxwbgmxgmert') # doctest: +ELLIPSIS
70 (19, -128.82410410...)
71 >>> caesar_break('yltbbqnqnzvguvaxurorgenafsbezqvagbnornfgsbevpnaabjurer' \
72 'svaquvzyvxrnznazlybequrvfohgriraabjtbaruraprur') # doctest: +ELLIPSIS
73 (13, -126.25403935...)
74 """
75 sanitised_message = sanitise(message)
76 best_shift = 0
77 best_fit = float('-inf')
78 for shift in range(26):
79 plaintext = caesar_decipher(sanitised_message, shift)
80 fit = fitness(plaintext)
81 logger.debug('Caesar break attempt using key {0} gives fit of {1} '
82 'and decrypt starting: {2}'.format(shift, fit, 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 {3} '
123 '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', Keyword_wrap_alphabet.from_last), \
135 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
136 (('elephant', <Keyword_wrap_alphabet.from_last: 2>), -52.834575011...)
137 """
138 best_keyword = ''
139 best_wrap_alphabet = True
140 best_fit = float("-inf")
141 for wrap_alphabet in Keyword_wrap_alphabet:
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, chunksize=500):
161 """Breaks a keyword substitution cipher using a dictionary and
162 frequency analysis
163
164 >>> keyword_break_mp(keyword_encipher('this is a test message for the ' \
165 'keyword decipherment', 'elephant', Keyword_wrap_alphabet.from_last), \
166 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
167 (('elephant', <Keyword_wrap_alphabet.from_last: 2>), -52.834575011...)
168 """
169 with Pool() as pool:
170 helper_args = [(message, word, wrap, fitness)
171 for word in wordlist
172 for wrap in Keyword_wrap_alphabet]
173 # Gotcha: the helper function here needs to be defined at the top level
174 # (limitation of Pool.starmap)
175 breaks = pool.starmap(keyword_break_worker, helper_args, chunksize)
176 return max(breaks, key=lambda k: k[1])
177
178 def keyword_break_worker(message, keyword, wrap_alphabet, fitness):
179 plaintext = keyword_decipher(message, keyword, wrap_alphabet)
180 fit = fitness(plaintext)
181 logger.debug('Keyword break attempt using key {0} (wrap={1}) gives fit of '
182 '{2} and decrypt starting: {3}'.format(keyword,
183 wrap_alphabet, fit, sanitise(plaintext)[:50]))
184 return (keyword, wrap_alphabet), fit
185
186
187 def column_transposition_break_mp(message, translist=transpositions,
188 fitness=Pbigrams, chunksize=500):
189 """Breaks a column transposition cipher using a dictionary and
190 n-gram frequency analysis
191
192 >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
193 "It is a truth universally acknowledged, that a single man in \
194 possession of a good fortune, must be in want of a wife. However \
195 little known the feelings or views of such a man may be on his \
196 first entering a neighbourhood, this truth is so well fixed in the \
197 minds of the surrounding families, that he is considered the \
198 rightful property of some one or other of their daughters."), \
199 'encipher'), \
200 translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
201 (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
202 (6, 1, 0, 4, 5, 3, 2): ['keyword']}) # doctest: +ELLIPSIS
203 (((2, 0, 5, 3, 1, 4, 6), False, False), -709.4646722...)
204 >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
205 "It is a truth universally acknowledged, that a single man in \
206 possession of a good fortune, must be in want of a wife. However \
207 little known the feelings or views of such a man may be on his \
208 first entering a neighbourhood, this truth is so well fixed in the \
209 minds of the surrounding families, that he is considered the \
210 rightful property of some one or other of their daughters."), \
211 'encipher'), \
212 translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
213 (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
214 (6, 1, 0, 4, 5, 3, 2): ['keyword']}, \
215 fitness=Ptrigrams) # doctest: +ELLIPSIS
216 (((2, 0, 5, 3, 1, 4, 6), False, False), -997.0129085...)
217 """
218 with Pool() as pool:
219 helper_args = [(message, trans, fillcolumnwise, emptycolumnwise,
220 fitness)
221 for trans in translist.keys()
222 for fillcolumnwise in [True, False]
223 for emptycolumnwise in [True, False]]
224 # Gotcha: the helper function here needs to be defined at the top level
225 # (limitation of Pool.starmap)
226 breaks = pool.starmap(column_transposition_break_worker,
227 helper_args, chunksize)
228 return max(breaks, key=lambda k: k[1])
229 column_transposition_break = column_transposition_break_mp
230
231 def column_transposition_break_worker(message, transposition,
232 fillcolumnwise, emptycolumnwise, fitness):
233 plaintext = column_transposition_decipher(message, transposition,
234 fillcolumnwise=fillcolumnwise, emptycolumnwise=emptycolumnwise)
235 fit = fitness(sanitise(plaintext))
236 logger.debug('Column transposition break attempt using key {0} '
237 'gives fit of {1} and decrypt starting: {2}'.format(
238 transposition, fit,
239 sanitise(plaintext)[:50]))
240 return (transposition, fillcolumnwise, emptycolumnwise), fit
241
242
243 def scytale_break_mp(message, max_key_length=20,
244 fitness=Pbigrams, chunksize=500):
245 """Breaks a scytale cipher using a range of lengths and
246 n-gram frequency analysis
247
248 >>> scytale_break_mp(scytale_encipher(sanitise( \
249 "It is a truth universally acknowledged, that a single man in \
250 possession of a good fortune, must be in want of a wife. However \
251 little known the feelings or views of such a man may be on his \
252 first entering a neighbourhood, this truth is so well fixed in the \
253 minds of the surrounding families, that he is considered the \
254 rightful property of some one or other of their daughters."), \
255 5)) # doctest: +ELLIPSIS
256 (5, -709.4646722...)
257 >>> scytale_break_mp(scytale_encipher(sanitise( \
258 "It is a truth universally acknowledged, that a single man in \
259 possession of a good fortune, must be in want of a wife. However \
260 little known the feelings or views of such a man may be on his \
261 first entering a neighbourhood, this truth is so well fixed in the \
262 minds of the surrounding families, that he is considered the \
263 rightful property of some one or other of their daughters."), \
264 5), \
265 fitness=Ptrigrams) # doctest: +ELLIPSIS
266 (5, -997.0129085...)
267 """
268 with Pool() as pool:
269 helper_args = [(message, trans, False, True, fitness)
270 for trans in
271 [[col for col in range(math.ceil(len(message)/rows))]
272 for rows in range(1,max_key_length+1)]]
273 # Gotcha: the helper function here needs to be defined at the top level
274 # (limitation of Pool.starmap)
275 breaks = pool.starmap(column_transposition_break_worker,
276 helper_args, chunksize)
277 best = max(breaks, key=lambda k: k[1])
278 return math.trunc(len(message) / len(best[0][0])), best[1]
279 scytale_break = scytale_break_mp
280
281
282 def vigenere_keyword_break_mp(message, wordlist=keywords, fitness=Pletters,
283 chunksize=500):
284 """Breaks a vigenere cipher using a dictionary and
285 frequency analysis
286
287 >>> vigenere_keyword_break_mp(vigenere_encipher(sanitise('this is a test ' \
288 'message for the vigenere decipherment'), 'cat'), \
289 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
290 ('cat', -52.947271216...)
291 """
292 with Pool() as pool:
293 helper_args = [(message, word, fitness)
294 for word in wordlist]
295 # Gotcha: the helper function here needs to be defined at the top level
296 # (limitation of Pool.starmap)
297 breaks = pool.starmap(vigenere_keyword_break_worker, helper_args, chunksize)
298 return max(breaks, key=lambda k: k[1])
299 vigenere_keyword_break = vigenere_keyword_break_mp
300
301 def vigenere_keyword_break_worker(message, keyword, fitness):
302 plaintext = vigenere_decipher(message, keyword)
303 fit = fitness(plaintext)
304 logger.debug('Vigenere keyword break attempt using key {0} gives fit of '
305 '{1} and decrypt starting: {2}'.format(keyword,
306 fit, sanitise(plaintext)[:50]))
307 return keyword, fit
308
309
310
311 def vigenere_frequency_break(message, max_key_length=20, fitness=Pletters):
312 """Breaks a Vigenere cipher with frequency analysis
313
314 >>> vigenere_frequency_break(vigenere_encipher(sanitise("It is time to " \
315 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
316 "afternoon when he left his jacket hanging on the easel in the " \
317 "attic. I jump every time I hear a footstep on the stairs, " \
318 "certain that the theft has been discovered and that I will " \
319 "be caught. The SS officer visits less often now that he is " \
320 "sure"), 'florence')) # doctest: +ELLIPSIS
321 ('florence', -307.5473096791...)
322 """
323 def worker(message, key_length, fitness):
324 splits = every_nth(sanitised_message, key_length)
325 key = ''.join([chr(caesar_break(s)[0] + ord('a')) for s in splits])
326 plaintext = vigenere_decipher(message, key)
327 fit = fitness(plaintext)
328 return key, fit
329 sanitised_message = sanitise(message)
330 results = starmap(worker, [(sanitised_message, i, fitness)
331 for i in range(1, max_key_length+1)])
332 return max(results, key=lambda k: k[1])
333
334
335 def beaufort_frequency_break(message, max_key_length=20, fitness=Pletters):
336 """Breaks a Beaufort cipher with frequency analysis
337
338 >>> beaufort_frequency_break(beaufort_encipher(sanitise("It is time to " \
339 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
340 "afternoon when he left his jacket hanging on the easel in the " \
341 "attic. I jump every time I hear a footstep on the stairs, " \
342 "certain that the theft has been discovered and that I will " \
343 "be caught. The SS officer visits less often now " \
344 "that he is sure"), 'florence')) # doctest: +ELLIPSIS
345 ('florence', -307.5473096791...)
346 """
347 def worker(message, key_length, fitness):
348 splits = every_nth(sanitised_message, key_length)
349 key = ''.join([chr(-caesar_break(s)[0] % 26 + ord('a')) for s in splits])
350 plaintext = beaufort_decipher(message, key)
351 fit = fitness(plaintext)
352 return key, fit
353 sanitised_message = sanitise(message)
354 results = starmap(worker, [(sanitised_message, i, fitness)
355 for i in range(1, max_key_length+1)])
356 return max(results, key=lambda k: k[1])
357
358
359 def plot_frequency_histogram(freqs, sort_key=None):
360 x = range(len(freqs.keys()))
361 y = [freqs[l] for l in sorted(freqs.keys(), key=sort_key)]
362 f = plt.figure()
363 ax = f.add_axes([0.1, 0.1, 0.9, 0.9])
364 ax.bar(x, y, align='center')
365 ax.set_xticks(x)
366 ax.set_xticklabels(sorted(freqs.keys(), key=sort_key))
367 f.show()
368
369
370 if __name__ == "__main__":
371 import doctest
372 doctest.testmod()
373