Included Python 3.4's Enum for keyword alphabets, added Pwords_wrong and friends...
[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
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: 1>), -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: 1>), -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 def scytale_break(message, fitness=Pbigrams):
187 """Breaks a Scytale cipher
188
189 >>> scytale_break('tfeulchtrtteehwahsdehneoifeayfsondmwpltmaoalhikotoere' \
190 'dcweatehiplwxsnhooacgorrcrcraotohsgullasenylrendaianeplscdriioto' \
191 'aek') # doctest: +ELLIPSIS
192 (6, -281.276219108...)
193 """
194 best_key = 0
195 best_fit = float("-inf")
196 for key in range(1, 20):
197 if len(message) % key == 0:
198 plaintext = scytale_decipher(message, key)
199 fit = fitness(sanitise(plaintext))
200 logger.debug('Scytale break attempt using key {0} gives fit of '
201 '{1} and decrypt starting: {2}'.format(key,
202 fit, sanitise(plaintext)[:50]))
203 if fit > best_fit:
204 best_fit = fit
205 best_key = key
206 logger.info('Scytale break best fit with key {0} gives fit of {1} and '
207 'decrypt starting: {2}'.format(best_key, best_fit,
208 sanitise(scytale_decipher(message, best_key))[:50]))
209 return best_key, best_fit
210
211
212 def column_transposition_break_mp(message, translist=transpositions,
213 fitness=Pbigrams, chunksize=500):
214 """Breaks a column transposition cipher using a dictionary and
215 n-gram frequency analysis
216 """
217 # >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
218 # "It is a truth universally acknowledged, that a single man in \
219 # possession of a good fortune, must be in want of a wife. However \
220 # little known the feelings or views of such a man may be on his \
221 # first entering a neighbourhood, this truth is so well fixed in the \
222 # minds of the surrounding families, that he is considered the \
223 # rightful property of some one or other of their daughters."), \
224 # 'encipher'), \
225 # translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
226 # (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
227 # (6, 1, 0, 4, 5, 3, 2): ['keyword']}) # doctest: +ELLIPSIS
228 # (((2, 0, 5, 3, 1, 4, 6), False), 0.0628106372...)
229 # >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
230 # "It is a truth universally acknowledged, that a single man in \
231 # possession of a good fortune, must be in want of a wife. However \
232 # little known the feelings or views of such a man may be on his \
233 # first entering a neighbourhood, this truth is so well fixed in the \
234 # minds of the surrounding families, that he is considered the \
235 # rightful property of some one or other of their daughters."), \
236 # 'encipher'), \
237 # translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
238 # (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
239 # (6, 1, 0, 4, 5, 3, 2): ['keyword']}, \
240 # target_counts=normalised_english_trigram_counts) # doctest: +ELLIPSIS
241 # (((2, 0, 5, 3, 1, 4, 6), False), 0.0592259560...)
242 # """
243 with Pool() as pool:
244 helper_args = [(message, trans, columnwise, fitness)
245 for trans in translist.keys()
246 for columnwise in [True, False]]
247 # Gotcha: the helper function here needs to be defined at the top level
248 # (limitation of Pool.starmap)
249 breaks = pool.starmap(column_transposition_break_worker,
250 helper_args, chunksize)
251 return max(breaks, key=lambda k: k[1])
252 column_transposition_break = column_transposition_break_mp
253
254 def column_transposition_break_worker(message, transposition, columnwise,
255 fitness):
256 plaintext = column_transposition_decipher(message, transposition, columnwise=columnwise)
257 fit = fitness(sanitise(plaintext))
258 logger.debug('Column transposition break attempt using key {0} '
259 'gives fit of {1} and decrypt starting: {2}'.format(
260 transposition, fit,
261 sanitise(plaintext)[:50]))
262 return (transposition, columnwise), fit
263
264
265 def transposition_break_exhaustive(message, fitness=Pbigrams):
266 best_transposition = ''
267 best_pw = float('-inf')
268 for keylength in range(1, 21):
269 if len(message) % keylength == 0:
270 for transposition in permutations(range(keylength)):
271 for columnwise in [True, False]:
272 plaintext = column_transposition_decipher(message,
273 transposition, columnwise=columnwise)
274 fit=fitness(plaintext)
275 logger.debug('Column transposition break attempt using key {0} {1} '
276 'gives fit of {2} and decrypt starting: {3}'.format(
277 transposition, columnwise, pw,
278 sanitise(plaintext)[:50]))
279 if fit > best_fit:
280 best_transposition = transposition
281 best_columnwise = columnwise
282 best_fit = fit
283 return (best_transposition, best_columnwise), best_pw
284
285
286 def vigenere_keyword_break(message, wordlist=keywords, fitness=Pletters):
287 """Breaks a vigenere cipher using a dictionary and
288 frequency analysis
289
290 >>> vigenere_keyword_break(vigenere_encipher(sanitise('this is a test ' \
291 'message for the vigenere decipherment'), 'cat'), \
292 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
293 ('cat', -52.947271216...)
294 """
295 best_keyword = ''
296 best_fit = float("-inf")
297 for keyword in wordlist:
298 plaintext = vigenere_decipher(message, keyword)
299 fit = fitness(plaintext)
300 logger.debug('Vigenere break attempt using key {0} '
301 'gives fit of {1} and decrypt starting: {2}'.format(
302 keyword, fit,
303 sanitise(plaintext)[:50]))
304 if fit > best_fit:
305 best_fit = fit
306 best_keyword = keyword
307 logger.info('Vigenere break best fit with key {0} gives fit '
308 'of {1} and decrypt starting: {2}'.format(best_keyword,
309 best_fit, sanitise(
310 vigenere_decipher(message, best_keyword))[:50]))
311 return best_keyword, best_fit
312
313 def vigenere_keyword_break_mp(message, wordlist=keywords, fitness=Pletters,
314 chunksize=500):
315 """Breaks a vigenere cipher using a dictionary and
316 frequency analysis
317
318 >>> vigenere_keyword_break_mp(vigenere_encipher(sanitise('this is a test ' \
319 'message for the vigenere decipherment'), 'cat'), \
320 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
321 ('cat', -52.947271216...)
322 """
323 with Pool() as pool:
324 helper_args = [(message, word, fitness)
325 for word in wordlist]
326 # Gotcha: the helper function here needs to be defined at the top level
327 # (limitation of Pool.starmap)
328 breaks = pool.starmap(vigenere_keyword_break_worker, helper_args, chunksize)
329 return max(breaks, key=lambda k: k[1])
330
331 def vigenere_keyword_break_worker(message, keyword, fitness):
332 plaintext = vigenere_decipher(message, keyword)
333 fit = fitness(plaintext)
334 logger.debug('Vigenere keyword break attempt using key {0} gives fit of '
335 '{1} and decrypt starting: {2}'.format(keyword,
336 fit, sanitise(plaintext)[:50]))
337 return keyword, fit
338
339
340
341 def vigenere_frequency_break(message, fitness=Pletters):
342 """Breaks a Vigenere cipher with frequency analysis
343
344 >>> vigenere_frequency_break(vigenere_encipher(sanitise("It is time to " \
345 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
346 "afternoon when he left his jacket hanging on the easel in the " \
347 "attic. I jump every time I hear a footstep on the stairs, " \
348 "certain that the theft has been discovered and that I will " \
349 "be caught. The SS officer visits less often now that he is " \
350 "sure"), 'florence')) # doctest: +ELLIPSIS
351 ('florence', -307.5473096791...)
352 """
353 best_fit = float("-inf")
354 best_key = ''
355 sanitised_message = sanitise(message)
356 for trial_length in range(1, 20):
357 splits = every_nth(sanitised_message, trial_length)
358 key = ''.join([chr(caesar_break(s)[0] + ord('a')) for s in splits])
359 plaintext = vigenere_decipher(sanitised_message, key)
360 fit = fitness(plaintext)
361 logger.debug('Vigenere key length of {0} ({1}) gives fit of {2}'.
362 format(trial_length, key, fit))
363 if fit > best_fit:
364 best_fit = fit
365 best_key = key
366 logger.info('Vigenere break best fit with key {0} gives fit '
367 'of {1} and decrypt starting: {2}'.format(best_key,
368 best_fit, sanitise(
369 vigenere_decipher(message, best_key))[:50]))
370 return best_key, best_fit
371
372 def beaufort_frequency_break(message, fitness=Pletters):
373 """Breaks a Beaufort cipher with frequency analysis
374
375 >>> beaufort_frequency_break(beaufort_encipher(sanitise("It is time to " \
376 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
377 "afternoon when he left his jacket hanging on the easel in the " \
378 "attic. I jump every time I hear a footstep on the stairs, " \
379 "certain that the theft has been discovered and that I will " \
380 "be caught. The SS officer visits less often now " \
381 "that he is sure"), 'florence')) # doctest: +ELLIPSIS
382 ('florence', -307.5473096791...)
383 """
384 best_fit = float("-inf")
385 best_key = ''
386 sanitised_message = sanitise(message)
387 for trial_length in range(1, 20):
388 splits = every_nth(sanitised_message, trial_length)
389 key = ''.join([chr(-caesar_break(s)[0] % 26 + ord('a')) for s in splits])
390 plaintext = beaufort_decipher(sanitised_message, key)
391 fit = fitness(plaintext)
392 logger.debug('Beaufort key length of {0} ({1}) gives fit of {2}'.
393 format(trial_length, key, fit))
394 if fit > best_fit:
395 best_fit = fit
396 best_key = key
397 logger.info('Beaufort break best fit with key {0} gives fit '
398 'of {1} and decrypt starting: {2}'.format(best_key,
399 best_fit, sanitise(
400 beaufort_decipher(message, best_key))[:50]))
401 return best_key, best_fit
402
403
404
405 def plot_frequency_histogram(freqs, sort_key=None):
406 x = range(len(freqs.keys()))
407 y = [freqs[l] for l in sorted(freqs.keys(), key=sort_key)]
408 f = plt.figure()
409 ax = f.add_axes([0.1, 0.1, 0.9, 0.9])
410 ax.bar(x, y, align='center')
411 ax.set_xticks(x)
412 ax.set_xticklabels(sorted(freqs.keys(), key=sort_key))
413 f.show()
414
415
416 if __name__ == "__main__":
417 import doctest
418 doctest.testmod()
419