Rearranged some code
[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, plaintext[:50]))
84 if fit > best_fit:
85 best_fit = fit
86 best_shift = shift
87 logger.info('Caesar break best fit: key {0} gives fit of {1} and '
88 'decrypt starting: {2}'.format(best_shift, best_fit,
89 caesar_decipher(sanitised_message, best_shift)[:50]))
90 return best_shift, best_fit
91
92 def affine_break(message, fitness=Pletters):
93 """Breaks an affine cipher using frequency analysis
94
95 >>> affine_break('lmyfu bkuusd dyfaxw claol psfaom jfasd snsfg jfaoe ls ' \
96 'omytd jlaxe mh jm bfmibj umis hfsul axubafkjamx. ls kffkxwsd jls ' \
97 'ofgbjmwfkiu olfmxmtmwaokttg jlsx ls kffkxwsd jlsi zg tsxwjl. jlsx ' \
98 'ls umfjsd jlsi zg hfsqysxog. ls dmmdtsd mx jls bats mh bkbsf. ls ' \
99 'bfmctsd kfmyxd jls lyj, mztanamyu xmc jm clm cku tmmeaxw kj lai ' \
100 'kxd clm ckuxj.') # doctest: +ELLIPSIS
101 ((15, 22, True), -340.601181913...)
102 """
103 sanitised_message = sanitise(message)
104 best_multiplier = 0
105 best_adder = 0
106 best_one_based = True
107 best_fit = float("-inf")
108 for one_based in [True, False]:
109 for multiplier in [x for x in range(1, 26, 2) if x != 13]:
110 for adder in range(26):
111 plaintext = affine_decipher(sanitised_message,
112 multiplier, adder, one_based)
113 fit = fitness(plaintext)
114 logger.debug('Affine break attempt using key {0}x+{1} ({2}) '
115 'gives fit of {3} and decrypt starting: {4}'.
116 format(multiplier, adder, one_based, fit,
117 plaintext[:50]))
118 if fit > best_fit:
119 best_fit = fit
120 best_multiplier = multiplier
121 best_adder = adder
122 best_one_based = one_based
123 logger.info('Affine break best fit with key {0}x+{1} ({2}) gives fit of {3} '
124 'and decrypt starting: {4}'.format(
125 best_multiplier, best_adder, best_one_based, best_fit,
126 affine_decipher(sanitised_message, best_multiplier,
127 best_adder, best_one_based)[:50]))
128 return (best_multiplier, best_adder, best_one_based), best_fit
129
130 def keyword_break(message, wordlist=keywords, fitness=Pletters):
131 """Breaks a keyword substitution cipher using a dictionary and
132 frequency analysis
133
134 >>> keyword_break(keyword_encipher('this is a test message for the ' \
135 'keyword decipherment', 'elephant', Keyword_wrap_alphabet.from_last), \
136 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
137 (('elephant', <Keyword_wrap_alphabet.from_last: 2>), -52.834575011...)
138 """
139 best_keyword = ''
140 best_wrap_alphabet = True
141 best_fit = float("-inf")
142 for wrap_alphabet in Keyword_wrap_alphabet:
143 for keyword in wordlist:
144 plaintext = keyword_decipher(message, keyword, wrap_alphabet)
145 fit = fitness(plaintext)
146 logger.debug('Keyword break attempt using key {0} (wrap={1}) '
147 'gives fit of {2} and decrypt starting: {3}'.format(
148 keyword, wrap_alphabet, fit,
149 sanitise(plaintext)[:50]))
150 if fit > best_fit:
151 best_fit = fit
152 best_keyword = keyword
153 best_wrap_alphabet = wrap_alphabet
154 logger.info('Keyword break best fit with key {0} (wrap={1}) gives fit of '
155 '{2} and decrypt starting: {3}'.format(best_keyword,
156 best_wrap_alphabet, best_fit, sanitise(
157 keyword_decipher(message, best_keyword,
158 best_wrap_alphabet))[:50]))
159 return (best_keyword, best_wrap_alphabet), best_fit
160
161 def keyword_break_mp(message, wordlist=keywords, fitness=Pletters, 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', Keyword_wrap_alphabet.from_last), \
167 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
168 (('elephant', <Keyword_wrap_alphabet.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 Keyword_wrap_alphabet]
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 def monoalphabetic_break_hillclimbing(message, max_iterations = 10000000,
188 fitness=Pletters):
189 ciphertext = unaccent(message).lower()
190 alphabet = list(string.ascii_lowercase)
191 random.shuffle(alphabet)
192 alphabet = ''.join(alphabet)
193 return monoalphabetic_break_hillclimbing_worker(ciphertext, alphabet,
194 max_iterations, fitness)
195
196 def monoalphabetic_break_hillclimbing_mp(message, workers=10,
197 max_iterations = 10000000, fitness=Pletters, chunksize=1):
198 worker_args = []
199 ciphertext = unaccent(message).lower()
200 for i in range(workers):
201 alphabet = list(string.ascii_lowercase)
202 random.shuffle(alphabet)
203 alphabet = ''.join(alphabet)
204 worker_args.append((ciphertext, alphabet, max_iterations, fitness))
205 with Pool() as pool:
206 breaks = pool.starmap(monoalphabetic_break_hillclimbing_worker,
207 worker_args, chunksize)
208 return max(breaks, key=lambda k: k[1])
209
210 def monoalphabetic_break_hillclimbing_worker(message, alphabet,
211 max_iterations, fitness):
212 def swap(letters, i, j):
213 if i > j:
214 i, j = j, i
215 if i == j:
216 return letters
217 else:
218 return letters[:i] + letters[j] + letters[i+1:j] + letters[i] + letters[j+1:]
219 best_alphabet = alphabet
220 best_fitness = float('-inf')
221 for i in range(max_iterations):
222 alphabet = swap(alphabet, random.randrange(26), random.randrange(26))
223 cipher_translation = ''.maketrans(string.ascii_lowercase, alphabet)
224 plaintext = message.translate(cipher_translation)
225 if fitness(plaintext) > best_fitness:
226 best_fitness = fitness(plaintext)
227 best_alphabet = alphabet
228 print(i, best_alphabet, best_fitness, plaintext)
229 return best_alphabet, best_fitness
230
231
232 def column_transposition_break_mp(message, translist=transpositions,
233 fitness=Pbigrams, chunksize=500):
234 """Breaks a column transposition cipher using a dictionary and
235 n-gram frequency analysis
236
237 >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
238 "It is a truth universally acknowledged, that a single man in \
239 possession of a good fortune, must be in want of a wife. However \
240 little known the feelings or views of such a man may be on his \
241 first entering a neighbourhood, this truth is so well fixed in the \
242 minds of the surrounding families, that he is considered the \
243 rightful property of some one or other of their daughters."), \
244 'encipher'), \
245 translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
246 (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
247 (6, 1, 0, 4, 5, 3, 2): ['keyword']}) # doctest: +ELLIPSIS
248 (((2, 0, 5, 3, 1, 4, 6), False, False), -709.4646722...)
249 >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
250 "It is a truth universally acknowledged, that a single man in \
251 possession of a good fortune, must be in want of a wife. However \
252 little known the feelings or views of such a man may be on his \
253 first entering a neighbourhood, this truth is so well fixed in the \
254 minds of the surrounding families, that he is considered the \
255 rightful property of some one or other of their daughters."), \
256 'encipher'), \
257 translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
258 (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
259 (6, 1, 0, 4, 5, 3, 2): ['keyword']}, \
260 fitness=Ptrigrams) # doctest: +ELLIPSIS
261 (((2, 0, 5, 3, 1, 4, 6), False, False), -997.0129085...)
262 """
263 with Pool() as pool:
264 helper_args = [(message, trans, fillcolumnwise, emptycolumnwise,
265 fitness)
266 for trans in translist.keys()
267 for fillcolumnwise in [True, False]
268 for emptycolumnwise in [True, False]]
269 # Gotcha: the helper function here needs to be defined at the top level
270 # (limitation of Pool.starmap)
271 breaks = pool.starmap(column_transposition_break_worker,
272 helper_args, chunksize)
273 return max(breaks, key=lambda k: k[1])
274 column_transposition_break = column_transposition_break_mp
275
276 def column_transposition_break_worker(message, transposition,
277 fillcolumnwise, emptycolumnwise, fitness):
278 plaintext = column_transposition_decipher(message, transposition,
279 fillcolumnwise=fillcolumnwise, emptycolumnwise=emptycolumnwise)
280 fit = fitness(sanitise(plaintext))
281 logger.debug('Column transposition break attempt using key {0} '
282 'gives fit of {1} and decrypt starting: {2}'.format(
283 transposition, fit,
284 sanitise(plaintext)[:50]))
285 return (transposition, fillcolumnwise, emptycolumnwise), fit
286
287
288 def scytale_break_mp(message, max_key_length=20,
289 fitness=Pbigrams, chunksize=500):
290 """Breaks a scytale cipher using a range of lengths and
291 n-gram frequency analysis
292
293 >>> scytale_break_mp(scytale_encipher(sanitise( \
294 "It is a truth universally acknowledged, that a single man in \
295 possession of a good fortune, must be in want of a wife. However \
296 little known the feelings or views of such a man may be on his \
297 first entering a neighbourhood, this truth is so well fixed in the \
298 minds of the surrounding families, that he is considered the \
299 rightful property of some one or other of their daughters."), \
300 5)) # doctest: +ELLIPSIS
301 (5, -709.4646722...)
302 >>> scytale_break_mp(scytale_encipher(sanitise( \
303 "It is a truth universally acknowledged, that a single man in \
304 possession of a good fortune, must be in want of a wife. However \
305 little known the feelings or views of such a man may be on his \
306 first entering a neighbourhood, this truth is so well fixed in the \
307 minds of the surrounding families, that he is considered the \
308 rightful property of some one or other of their daughters."), \
309 5), \
310 fitness=Ptrigrams) # doctest: +ELLIPSIS
311 (5, -997.0129085...)
312 """
313 with Pool() as pool:
314 helper_args = [(message, trans, False, True, fitness)
315 for trans in
316 [[col for col in range(math.ceil(len(message)/rows))]
317 for rows in range(1,max_key_length+1)]]
318 # Gotcha: the helper function here needs to be defined at the top level
319 # (limitation of Pool.starmap)
320 breaks = pool.starmap(column_transposition_break_worker,
321 helper_args, chunksize)
322 best = max(breaks, key=lambda k: k[1])
323 return math.trunc(len(message) / len(best[0][0])), best[1]
324 scytale_break = scytale_break_mp
325
326
327 def vigenere_keyword_break_mp(message, wordlist=keywords, fitness=Pletters,
328 chunksize=500):
329 """Breaks a vigenere cipher using a dictionary and
330 frequency analysis
331
332 >>> vigenere_keyword_break_mp(vigenere_encipher(sanitise('this is a test ' \
333 'message for the vigenere decipherment'), 'cat'), \
334 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
335 ('cat', -52.947271216...)
336 """
337 with Pool() as pool:
338 helper_args = [(message, word, fitness)
339 for word in wordlist]
340 # Gotcha: the helper function here needs to be defined at the top level
341 # (limitation of Pool.starmap)
342 breaks = pool.starmap(vigenere_keyword_break_worker, helper_args, chunksize)
343 return max(breaks, key=lambda k: k[1])
344 vigenere_keyword_break = vigenere_keyword_break_mp
345
346 def vigenere_keyword_break_worker(message, keyword, fitness):
347 plaintext = vigenere_decipher(message, keyword)
348 fit = fitness(plaintext)
349 logger.debug('Vigenere keyword break attempt using key {0} gives fit of '
350 '{1} and decrypt starting: {2}'.format(keyword,
351 fit, sanitise(plaintext)[:50]))
352 return keyword, fit
353
354
355
356 def vigenere_frequency_break(message, max_key_length=20, fitness=Pletters):
357 """Breaks a Vigenere cipher with frequency analysis
358
359 >>> vigenere_frequency_break(vigenere_encipher(sanitise("It is time to " \
360 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
361 "afternoon when he left his jacket hanging on the easel in the " \
362 "attic. I jump every time I hear a footstep on the stairs, " \
363 "certain that the theft has been discovered and that I will " \
364 "be caught. The SS officer visits less often now that he is " \
365 "sure"), 'florence')) # doctest: +ELLIPSIS
366 ('florence', -307.5473096791...)
367 """
368 def worker(message, key_length, fitness):
369 splits = every_nth(sanitised_message, key_length)
370 key = ''.join([chr(caesar_break(s)[0] + ord('a')) for s in splits])
371 plaintext = vigenere_decipher(message, key)
372 fit = fitness(plaintext)
373 return key, fit
374 sanitised_message = sanitise(message)
375 results = starmap(worker, [(sanitised_message, i, fitness)
376 for i in range(1, max_key_length+1)])
377 return max(results, key=lambda k: k[1])
378
379
380 def beaufort_frequency_break(message, max_key_length=20, fitness=Pletters):
381 """Breaks a Beaufort cipher with frequency analysis
382
383 >>> beaufort_frequency_break(beaufort_encipher(sanitise("It is time to " \
384 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
385 "afternoon when he left his jacket hanging on the easel in the " \
386 "attic. I jump every time I hear a footstep on the stairs, " \
387 "certain that the theft has been discovered and that I will " \
388 "be caught. The SS officer visits less often now " \
389 "that he is sure"), 'florence')) # doctest: +ELLIPSIS
390 ('florence', -307.5473096791...)
391 """
392 def worker(message, key_length, fitness):
393 splits = every_nth(sanitised_message, key_length)
394 key = ''.join([chr(-caesar_break(s)[0] % 26 + ord('a')) for s in splits])
395 plaintext = beaufort_decipher(message, key)
396 fit = fitness(plaintext)
397 return key, fit
398 sanitised_message = sanitise(message)
399 results = starmap(worker, [(sanitised_message, i, fitness)
400 for i in range(1, max_key_length+1)])
401 return max(results, key=lambda k: k[1])
402
403
404 def plot_frequency_histogram(freqs, sort_key=None):
405 x = range(len(freqs.keys()))
406 y = [freqs[l] for l in sorted(freqs.keys(), key=sort_key)]
407 f = plt.figure()
408 ax = f.add_axes([0.1, 0.1, 0.9, 0.9])
409 ax.bar(x, y, align='center')
410 ax.set_xticks(x)
411 ax.set_xticklabels(sorted(freqs.keys(), key=sort_key))
412 f.show()
413
414
415 if __name__ == "__main__":
416 import doctest
417 doctest.testmod()
418