Merge branch 'development' into solutions
[cipher-training.git] / cipherbreak.py
1 import string
2 import collections
3 import norms
4 import logging
5 import random
6 from itertools import zip_longest, cycle, permutations, starmap
7 from segment import segment
8 from multiprocessing import Pool
9 from math import log10
10
11 import matplotlib.pyplot as plt
12
13 logger = logging.getLogger(__name__)
14 logger.addHandler(logging.FileHandler('cipher.log'))
15 logger.setLevel(logging.WARNING)
16 #logger.setLevel(logging.INFO)
17 #logger.setLevel(logging.DEBUG)
18
19 from cipher import *
20 from language_models import *
21
22 # To time a run:
23 #
24 # import timeit
25 # c5a = open('2012/5a.ciphertext', 'r').read()
26 # timeit.timeit('keyword_break(c5a)', setup='gc.enable() ; from __main__ import c5a ; from cipher import keyword_break', number=1)
27 # 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)
28
29 transpositions = collections.defaultdict(list)
30 for word in keywords:
31 transpositions[transpositions_of(word)] += [word]
32
33 def frequencies(text):
34 """Count the number of occurrences of each character in text
35
36 >>> sorted(frequencies('abcdefabc').items())
37 [('a', 2), ('b', 2), ('c', 2), ('d', 1), ('e', 1), ('f', 1)]
38 >>> sorted(frequencies('the quick brown fox jumped over the lazy ' \
39 'dog').items()) # doctest: +NORMALIZE_WHITESPACE
40 [(' ', 8), ('a', 1), ('b', 1), ('c', 1), ('d', 2), ('e', 4), ('f', 1),
41 ('g', 1), ('h', 2), ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1),
42 ('n', 1), ('o', 4), ('p', 1), ('q', 1), ('r', 2), ('t', 2), ('u', 2),
43 ('v', 1), ('w', 1), ('x', 1), ('y', 1), ('z', 1)]
44 >>> sorted(frequencies('The Quick BROWN fox jumped! over... the ' \
45 '(9lazy) DOG').items()) # doctest: +NORMALIZE_WHITESPACE
46 [(' ', 8), ('!', 1), ('(', 1), (')', 1), ('.', 3), ('9', 1), ('B', 1),
47 ('D', 1), ('G', 1), ('N', 1), ('O', 2), ('Q', 1), ('R', 1), ('T', 1),
48 ('W', 1), ('a', 1), ('c', 1), ('d', 1), ('e', 4), ('f', 1), ('h', 2),
49 ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1), ('o', 2), ('p', 1),
50 ('r', 1), ('t', 1), ('u', 2), ('v', 1), ('x', 1), ('y', 1), ('z', 1)]
51 >>> sorted(frequencies(sanitise('The Quick BROWN fox jumped! over... '\
52 'the (9lazy) DOG')).items()) # doctest: +NORMALIZE_WHITESPACE
53 [('a', 1), ('b', 1), ('c', 1), ('d', 2), ('e', 4), ('f', 1), ('g', 1),
54 ('h', 2), ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1), ('n', 1),
55 ('o', 4), ('p', 1), ('q', 1), ('r', 2), ('t', 2), ('u', 2), ('v', 1),
56 ('w', 1), ('x', 1), ('y', 1), ('z', 1)]
57 >>> frequencies('abcdefabcdef')['x']
58 0
59 """
60 return collections.Counter(c for c in text)
61
62
63 def caesar_break(message, fitness=Pletters):
64 """Breaks a Caesar cipher using frequency analysis
65
66 >>> caesar_break('ibxcsyorsaqcheyklxivoexlevmrimwxsfiqevvmihrsasrxliwyrh' \
67 'ecjsppsamrkwleppfmergefifvmhixscsymjcsyqeoixlm') # doctest: +ELLIPSIS
68 (4, -130.849989015...)
69 >>> caesar_break('wxwmaxdgheetgwuxztgptedbgznitgwwhpguxyhkxbmhvvtlbhgtee' \
70 'raxlmhiixweblmxgxwmhmaxybkbgztgwztsxwbgmxgmert') # doctest: +ELLIPSIS
71 (19, -128.82410410...)
72 >>> caesar_break('yltbbqnqnzvguvaxurorgenafsbezqvagbnornfgsbevpnaabjurer' \
73 'svaquvzyvxrnznazlybequrvfohgriraabjtbaruraprur') # doctest: +ELLIPSIS
74 (13, -126.25403935...)
75 """
76 sanitised_message = sanitise(message)
77 best_shift = 0
78 best_fit = float('-inf')
79 for shift in range(26):
80 plaintext = caesar_decipher(sanitised_message, shift)
81 fit = fitness(plaintext)
82 logger.debug('Caesar break attempt using key {0} gives fit of {1} '
83 'and decrypt starting: {2}'.format(shift, fit,
84 plaintext[:50]))
85 if fit > best_fit:
86 best_fit = fit
87 best_shift = shift
88 logger.info('Caesar break best fit: key {0} gives fit of {1} and '
89 'decrypt starting: {2}'.format(best_shift, best_fit,
90 caesar_decipher(sanitised_message, best_shift)[:50]))
91 return best_shift, best_fit
92
93 def affine_break(message, fitness=Pletters):
94 """Breaks an affine cipher using frequency analysis
95
96 >>> affine_break('lmyfu bkuusd dyfaxw claol psfaom jfasd snsfg jfaoe ls ' \
97 'omytd jlaxe mh jm bfmibj umis hfsul axubafkjamx. ls kffkxwsd jls ' \
98 'ofgbjmwfkiu olfmxmtmwaokttg jlsx ls kffkxwsd jlsi zg tsxwjl. jlsx ' \
99 'ls umfjsd jlsi zg hfsqysxog. ls dmmdtsd mx jls bats mh bkbsf. ls ' \
100 'bfmctsd kfmyxd jls lyj, mztanamyu xmc jm clm cku tmmeaxw kj lai ' \
101 'kxd clm ckuxj.') # doctest: +ELLIPSIS
102 ((15, 22, True), -340.601181913...)
103 """
104 sanitised_message = sanitise(message)
105 best_multiplier = 0
106 best_adder = 0
107 best_one_based = True
108 best_fit = float("-inf")
109 for one_based in [True, False]:
110 for multiplier in [x for x in range(1, 26, 2) if x != 13]:
111 for adder in range(26):
112 plaintext = affine_decipher(sanitised_message,
113 multiplier, adder, one_based)
114 fit = fitness(plaintext)
115 logger.debug('Affine break attempt using key {0}x+{1} ({2}) '
116 'gives fit of {3} and decrypt starting: {4}'.
117 format(multiplier, adder, one_based, fit,
118 plaintext[:50]))
119 if fit > best_fit:
120 best_fit = fit
121 best_multiplier = multiplier
122 best_adder = adder
123 best_one_based = one_based
124 logger.info('Affine break best fit with key {0}x+{1} ({2}) gives fit of '
125 '{3} and decrypt starting: {4}'.format(
126 best_multiplier, best_adder, best_one_based, best_fit,
127 affine_decipher(sanitised_message, best_multiplier,
128 best_adder, best_one_based)[:50]))
129 return (best_multiplier, best_adder, best_one_based), best_fit
130
131 def keyword_break(message, wordlist=keywords, fitness=Pletters):
132 """Breaks a keyword substitution cipher using a dictionary and
133 frequency analysis
134
135 >>> keyword_break(keyword_encipher('this is a test message for the ' \
136 'keyword decipherment', 'elephant', Keyword_wrap_alphabet.from_last), \
137 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
138 (('elephant', <Keyword_wrap_alphabet.from_last: 2>), -52.834575011...)
139 """
140 best_keyword = ''
141 best_wrap_alphabet = True
142 best_fit = float("-inf")
143 for wrap_alphabet in Keyword_wrap_alphabet:
144 for keyword in wordlist:
145 plaintext = keyword_decipher(message, keyword, wrap_alphabet)
146 fit = fitness(plaintext)
147 logger.debug('Keyword break attempt using key {0} (wrap={1}) '
148 'gives fit of {2} and decrypt starting: {3}'.format(
149 keyword, wrap_alphabet, fit,
150 sanitise(plaintext)[:50]))
151 if fit > best_fit:
152 best_fit = fit
153 best_keyword = keyword
154 best_wrap_alphabet = wrap_alphabet
155 logger.info('Keyword break best fit with key {0} (wrap={1}) gives fit of '
156 '{2} and decrypt starting: {3}'.format(best_keyword,
157 best_wrap_alphabet, best_fit, sanitise(
158 keyword_decipher(message, best_keyword,
159 best_wrap_alphabet))[:50]))
160 return (best_keyword, best_wrap_alphabet), best_fit
161
162 def keyword_break_mp(message, wordlist=keywords, fitness=Pletters, chunksize=500):
163 """Breaks a keyword substitution cipher using a dictionary and
164 frequency analysis
165
166 >>> keyword_break_mp(keyword_encipher('this is a test message for the ' \
167 'keyword decipherment', 'elephant', Keyword_wrap_alphabet.from_last), \
168 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
169 (('elephant', <Keyword_wrap_alphabet.from_last: 2>), -52.834575011...)
170 """
171 with Pool() as pool:
172 helper_args = [(message, word, wrap, fitness)
173 for word in wordlist
174 for wrap in Keyword_wrap_alphabet]
175 # Gotcha: the helper function here needs to be defined at the top level
176 # (limitation of Pool.starmap)
177 breaks = pool.starmap(keyword_break_worker, helper_args, chunksize)
178 return max(breaks, key=lambda k: k[1])
179
180 def keyword_break_worker(message, keyword, wrap_alphabet, fitness):
181 plaintext = keyword_decipher(message, keyword, wrap_alphabet)
182 fit = fitness(plaintext)
183 logger.debug('Keyword break attempt using key {0} (wrap={1}) gives fit of '
184 '{2} and decrypt starting: {3}'.format(keyword,
185 wrap_alphabet, fit, sanitise(plaintext)[:50]))
186 return (keyword, wrap_alphabet), fit
187
188 def monoalphabetic_break_hillclimbing(message, max_iterations = 10000000,
189 fitness=Pletters):
190 ciphertext = unaccent(message).lower()
191 alphabet = list(string.ascii_lowercase)
192 random.shuffle(alphabet)
193 alphabet = ''.join(alphabet)
194 return monoalphabetic_break_hillclimbing_worker(ciphertext, alphabet,
195 max_iterations, fitness)
196
197 def monoalphabetic_break_hillclimbing_mp(message, workers=10,
198 max_iterations = 10000000, fitness=Pletters, chunksize=1):
199 worker_args = []
200 ciphertext = unaccent(message).lower()
201 for i in range(workers):
202 alphabet = list(string.ascii_lowercase)
203 random.shuffle(alphabet)
204 alphabet = ''.join(alphabet)
205 worker_args.append((ciphertext, alphabet, max_iterations, fitness))
206 with Pool() as pool:
207 breaks = pool.starmap(monoalphabetic_break_hillclimbing_worker,
208 worker_args, chunksize)
209 return max(breaks, key=lambda k: k[1])
210
211 def monoalphabetic_break_hillclimbing_worker(message, alphabet,
212 max_iterations, fitness):
213 def swap(letters, i, j):
214 if i > j:
215 i, j = j, i
216 if i == j:
217 return letters
218 else:
219 return letters[:i] + letters[j] + letters[i+1:j] +
220 letters[i] + letters[j+1:]
221 best_alphabet = alphabet
222 best_fitness = float('-inf')
223 for i in range(max_iterations):
224 alphabet = swap(alphabet, random.randrange(26), random.randrange(26))
225 cipher_translation = ''.maketrans(string.ascii_lowercase, alphabet)
226 plaintext = message.translate(cipher_translation)
227 if fitness(plaintext) > best_fitness:
228 best_fitness = fitness(plaintext)
229 best_alphabet = alphabet
230 print(i, best_alphabet, best_fitness, plaintext)
231 return best_alphabet, best_fitness
232
233
234 def column_transposition_break_mp(message, translist=transpositions,
235 fitness=Pbigrams, chunksize=500):
236 """Breaks a column transposition cipher using a dictionary and
237 n-gram frequency analysis
238
239 >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
240 "It is a truth universally acknowledged, that a single man in \
241 possession of a good fortune, must be in want of a wife. However \
242 little known the feelings or views of such a man may be on his \
243 first entering a neighbourhood, this truth is so well fixed in the \
244 minds of the surrounding families, that he is considered the \
245 rightful property of some one or other of their daughters."), \
246 'encipher'), \
247 translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
248 (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
249 (6, 1, 0, 4, 5, 3, 2): ['keyword']}) # doctest: +ELLIPSIS
250 (((2, 0, 5, 3, 1, 4, 6), False, False), -709.4646722...)
251 >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
252 "It is a truth universally acknowledged, that a single man in \
253 possession of a good fortune, must be in want of a wife. However \
254 little known the feelings or views of such a man may be on his \
255 first entering a neighbourhood, this truth is so well fixed in the \
256 minds of the surrounding families, that he is considered the \
257 rightful property of some one or other of their daughters."), \
258 'encipher'), \
259 translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
260 (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
261 (6, 1, 0, 4, 5, 3, 2): ['keyword']}, \
262 fitness=Ptrigrams) # doctest: +ELLIPSIS
263 (((2, 0, 5, 3, 1, 4, 6), False, False), -997.0129085...)
264 """
265 with Pool() as pool:
266 helper_args = [(message, trans, fillcolumnwise, emptycolumnwise,
267 fitness)
268 for trans in translist.keys()
269 for fillcolumnwise in [True, False]
270 for emptycolumnwise in [True, False]]
271 # Gotcha: the helper function here needs to be defined at the top level
272 # (limitation of Pool.starmap)
273 breaks = pool.starmap(column_transposition_break_worker,
274 helper_args, chunksize)
275 return max(breaks, key=lambda k: k[1])
276 column_transposition_break = column_transposition_break_mp
277
278 def column_transposition_break_worker(message, transposition,
279 fillcolumnwise, emptycolumnwise, fitness):
280 plaintext = column_transposition_decipher(message, transposition,
281 fillcolumnwise=fillcolumnwise, emptycolumnwise=emptycolumnwise)
282 fit = fitness(sanitise(plaintext))
283 logger.debug('Column transposition break attempt using key {0} '
284 'gives fit of {1} and decrypt starting: {2}'.format(
285 transposition, fit,
286 sanitise(plaintext)[:50]))
287 return (transposition, fillcolumnwise, emptycolumnwise), fit
288
289
290 def scytale_break_mp(message, max_key_length=20,
291 fitness=Pbigrams, chunksize=500):
292 """Breaks a scytale cipher using a range of lengths and
293 n-gram frequency analysis
294
295 >>> scytale_break_mp(scytale_encipher(sanitise( \
296 "It is a truth universally acknowledged, that a single man in \
297 possession of a good fortune, must be in want of a wife. However \
298 little known the feelings or views of such a man may be on his \
299 first entering a neighbourhood, this truth is so well fixed in the \
300 minds of the surrounding families, that he is considered the \
301 rightful property of some one or other of their daughters."), \
302 5)) # doctest: +ELLIPSIS
303 (5, -709.4646722...)
304 >>> scytale_break_mp(scytale_encipher(sanitise( \
305 "It is a truth universally acknowledged, that a single man in \
306 possession of a good fortune, must be in want of a wife. However \
307 little known the feelings or views of such a man may be on his \
308 first entering a neighbourhood, this truth is so well fixed in the \
309 minds of the surrounding families, that he is considered the \
310 rightful property of some one or other of their daughters."), \
311 5), \
312 fitness=Ptrigrams) # doctest: +ELLIPSIS
313 (5, -997.0129085...)
314 """
315 with Pool() as pool:
316 helper_args = [(message, trans, False, True, fitness)
317 for trans in
318 [[col for col in range(math.ceil(len(message)/rows))]
319 for rows in range(1,max_key_length+1)]]
320 # Gotcha: the helper function here needs to be defined at the top level
321 # (limitation of Pool.starmap)
322 breaks = pool.starmap(column_transposition_break_worker,
323 helper_args, chunksize)
324 best = max(breaks, key=lambda k: k[1])
325 return math.trunc(len(message) / len(best[0][0])), best[1]
326 scytale_break = scytale_break_mp
327
328
329 def vigenere_keyword_break_mp(message, wordlist=keywords, fitness=Pletters,
330 chunksize=500):
331 """Breaks a vigenere cipher using a dictionary and
332 frequency analysis
333
334 >>> vigenere_keyword_break_mp(vigenere_encipher(sanitise('this is a test ' \
335 'message for the vigenere decipherment'), 'cat'), \
336 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
337 ('cat', -52.947271216...)
338 """
339 with Pool() as pool:
340 helper_args = [(message, word, fitness)
341 for word in wordlist]
342 # Gotcha: the helper function here needs to be defined at the top level
343 # (limitation of Pool.starmap)
344 breaks = pool.starmap(vigenere_keyword_break_worker, helper_args, chunksize)
345 return max(breaks, key=lambda k: k[1])
346 vigenere_keyword_break = vigenere_keyword_break_mp
347
348 def vigenere_keyword_break_worker(message, keyword, fitness):
349 plaintext = vigenere_decipher(message, keyword)
350 fit = fitness(plaintext)
351 logger.debug('Vigenere keyword break attempt using key {0} gives fit of '
352 '{1} and decrypt starting: {2}'.format(keyword,
353 fit, sanitise(plaintext)[:50]))
354 return keyword, fit
355
356
357
358 def vigenere_frequency_break(message, max_key_length=20, fitness=Pletters):
359 """Breaks a Vigenere cipher with frequency analysis
360
361 >>> vigenere_frequency_break(vigenere_encipher(sanitise("It is time to " \
362 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
363 "afternoon when he left his jacket hanging on the easel in the " \
364 "attic. I jump every time I hear a footstep on the stairs, " \
365 "certain that the theft has been discovered and that I will " \
366 "be caught. The SS officer visits less often now that he is " \
367 "sure"), 'florence')) # doctest: +ELLIPSIS
368 ('florence', -307.5473096791...)
369 """
370 def worker(message, key_length, fitness):
371 splits = every_nth(sanitised_message, key_length)
372 key = ''.join([chr(caesar_break(s)[0] + ord('a')) for s in splits])
373 plaintext = vigenere_decipher(message, key)
374 fit = fitness(plaintext)
375 return key, fit
376 sanitised_message = sanitise(message)
377 results = starmap(worker, [(sanitised_message, i, fitness)
378 for i in range(1, max_key_length+1)])
379 return max(results, key=lambda k: k[1])
380
381
382 def beaufort_frequency_break(message, max_key_length=20, fitness=Pletters):
383 """Breaks a Beaufort cipher with frequency analysis
384
385 >>> beaufort_frequency_break(beaufort_encipher(sanitise("It is time to " \
386 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
387 "afternoon when he left his jacket hanging on the easel in the " \
388 "attic. I jump every time I hear a footstep on the stairs, " \
389 "certain that the theft has been discovered and that I will " \
390 "be caught. The SS officer visits less often now " \
391 "that he is sure"), 'florence')) # doctest: +ELLIPSIS
392 ('florence', -307.5473096791...)
393 """
394 def worker(message, key_length, fitness):
395 splits = every_nth(sanitised_message, key_length)
396 key = ''.join([chr(-caesar_break(s)[0] % 26 + ord('a')) for s in splits])
397 plaintext = beaufort_decipher(message, key)
398 fit = fitness(plaintext)
399 return key, fit
400 sanitised_message = sanitise(message)
401 results = starmap(worker, [(sanitised_message, i, fitness)
402 for i in range(1, max_key_length+1)])
403 return max(results, key=lambda k: k[1])
404
405
406 def pocket_enigma_break_by_crib(message, wheel_spec, crib, crib_position):
407 """Break a pocket enigma using a crib (some plaintext that's expected to
408 be in a certain position). Returns a list of possible starting wheel
409 positions that could produce the crib.
410
411 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'h', 0)
412 ['a', 'f', 'q']
413 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'he', 0)
414 ['a']
415 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'll', 2)
416 ['a']
417 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'l', 2)
418 ['a']
419 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'l', 3)
420 ['a', 'j', 'n']
421 >>> pocket_enigma_break_by_crib('aaaaa', 1, 'l', 3)
422 []
423 """
424 pe = PocketEnigma(wheel=wheel_spec)
425 possible_positions = []
426 for p in string.ascii_lowercase:
427 pe.set_position(p)
428 plaintext = pe.decipher(message)
429 if plaintext[crib_position:crib_position+len(crib)] == crib:
430 possible_positions += [p]
431 return possible_positions
432
433
434 def plot_frequency_histogram(freqs, sort_key=None):
435 x = range(len(freqs.keys()))
436 y = [freqs[l] for l in sorted(freqs.keys(), key=sort_key)]
437 f = plt.figure()
438 ax = f.add_axes([0.1, 0.1, 0.9, 0.9])
439 ax.bar(x, y, align='center')
440 ax.set_xticks(x)
441 ax.set_xticklabels(sorted(freqs.keys(), key=sort_key))
442 f.show()
443
444
445 if __name__ == "__main__":
446 import doctest
447 doctest.testmod()