5 from itertools
import zip_longest
, cycle
, permutations
6 from segment
import segment
7 from multiprocessing
import Pool
10 import matplotlib
.pyplot
as plt
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)
19 from language_models
import *
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)
28 transpositions
= collections
.defaultdict(list)
30 transpositions
[transpositions_of(word
)] += [word
]
32 def frequencies(text
):
33 """Count the number of occurrences of each character in text
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']
59 return collections
.Counter(c
for c
in text
)
62 def caesar_break(message
, fitness
=Pletters
):
63 """Breaks a Caesar cipher using frequency analysis
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...)
75 sanitised_message
= sanitise(message
)
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]))
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
91 def affine_break(message
, fitness
=Pletters
):
92 """Breaks an affine cipher using frequency analysis
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...)
102 sanitised_message
= sanitise(message
)
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
,
119 best_multiplier
= multiplier
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
129 def keyword_break(message
, wordlist
=keywords
, fitness
=Pletters
):
130 """Breaks a keyword substitution cipher using a dictionary and
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...)
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]))
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
160 def keyword_break_mp(message
, wordlist
=keywords
, fitness
=Pletters
, chunksize
=500):
161 """Breaks a keyword substitution cipher using a dictionary and
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...)
170 helper_args
= [(message
, word
, wrap
, fitness
)
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])
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
186 def scytale_break(message
, fitness
=Pbigrams
):
187 """Breaks a Scytale cipher
189 >>> scytale_break('tfeulchtrtteehwahsdehneoifeayfsondmwpltmaoalhikotoere' \
190 'dcweatehiplwxsnhooacgorrcrcraotohsgullasenylrendaianeplscdriioto' \
191 'aek') # doctest: +ELLIPSIS
192 (6, -281.276219108...)
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]))
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
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
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."), \
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, False), -709.4646722...)
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."), \
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 fitness=Ptrigrams) # doctest: +ELLIPSIS
241 (((2, 0, 5, 3, 1, 4, 6), False, False), -997.0129085...)
244 helper_args
= [(message
, trans
, fillcolumnwise
, emptycolumnwise
,
246 for trans
in translist
.keys()
247 for fillcolumnwise
in [True, False]
248 for emptycolumnwise
in [True, False]]
249 # Gotcha: the helper function here needs to be defined at the top level
250 # (limitation of Pool.starmap)
251 breaks
= pool
.starmap(column_transposition_break_worker
,
252 helper_args
, chunksize
)
253 return max(breaks
, key
=lambda k
: k
[1])
254 column_transposition_break
= column_transposition_break_mp
256 def column_transposition_break_worker(message
, transposition
,
257 fillcolumnwise
, emptycolumnwise
, fitness
):
258 plaintext
= column_transposition_decipher(message
, transposition
,
259 fillcolumnwise
=fillcolumnwise
, emptycolumnwise
=emptycolumnwise
)
260 fit
= fitness(sanitise(plaintext
))
261 logger
.debug('Column transposition break attempt using key {0} '
262 'gives fit of {1} and decrypt starting: {2}'.format(
264 sanitise(plaintext
)[:50]))
265 return (transposition
, fillcolumnwise
, emptycolumnwise
), fit
269 def vigenere_keyword_break(message
, wordlist
=keywords
, fitness
=Pletters
):
270 """Breaks a vigenere cipher using a dictionary and
273 >>> vigenere_keyword_break(vigenere_encipher(sanitise('this is a test ' \
274 'message for the vigenere decipherment'), 'cat'), \
275 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
276 ('cat', -52.947271216...)
279 best_fit
= float("-inf")
280 for keyword
in wordlist
:
281 plaintext
= vigenere_decipher(message
, keyword
)
282 fit
= fitness(plaintext
)
283 logger
.debug('Vigenere break attempt using key {0} '
284 'gives fit of {1} and decrypt starting: {2}'.format(
286 sanitise(plaintext
)[:50]))
289 best_keyword
= keyword
290 logger
.info('Vigenere break best fit with key {0} gives fit '
291 'of {1} and decrypt starting: {2}'.format(best_keyword
,
293 vigenere_decipher(message
, best_keyword
))[:50]))
294 return best_keyword
, best_fit
296 def vigenere_keyword_break_mp(message
, wordlist
=keywords
, fitness
=Pletters
,
298 """Breaks a vigenere cipher using a dictionary and
301 >>> vigenere_keyword_break_mp(vigenere_encipher(sanitise('this is a test ' \
302 'message for the vigenere decipherment'), 'cat'), \
303 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
304 ('cat', -52.947271216...)
307 helper_args
= [(message
, word
, fitness
)
308 for word
in wordlist
]
309 # Gotcha: the helper function here needs to be defined at the top level
310 # (limitation of Pool.starmap)
311 breaks
= pool
.starmap(vigenere_keyword_break_worker
, helper_args
, chunksize
)
312 return max(breaks
, key
=lambda k
: k
[1])
314 def vigenere_keyword_break_worker(message
, keyword
, fitness
):
315 plaintext
= vigenere_decipher(message
, keyword
)
316 fit
= fitness(plaintext
)
317 logger
.debug('Vigenere keyword break attempt using key {0} gives fit of '
318 '{1} and decrypt starting: {2}'.format(keyword
,
319 fit
, sanitise(plaintext
)[:50]))
324 def vigenere_frequency_break(message
, fitness
=Pletters
):
325 """Breaks a Vigenere cipher with frequency analysis
327 >>> vigenere_frequency_break(vigenere_encipher(sanitise("It is time to " \
328 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
329 "afternoon when he left his jacket hanging on the easel in the " \
330 "attic. I jump every time I hear a footstep on the stairs, " \
331 "certain that the theft has been discovered and that I will " \
332 "be caught. The SS officer visits less often now that he is " \
333 "sure"), 'florence')) # doctest: +ELLIPSIS
334 ('florence', -307.5473096791...)
336 best_fit
= float("-inf")
338 sanitised_message
= sanitise(message
)
339 for trial_length
in range(1, 20):
340 splits
= every_nth(sanitised_message
, trial_length
)
341 key
= ''.join([chr(caesar_break(s
)[0] + ord('a')) for s
in splits
])
342 plaintext
= vigenere_decipher(sanitised_message
, key
)
343 fit
= fitness(plaintext
)
344 logger
.debug('Vigenere key length of {0} ({1}) gives fit of {2}'.
345 format(trial_length
, key
, fit
))
349 logger
.info('Vigenere break best fit with key {0} gives fit '
350 'of {1} and decrypt starting: {2}'.format(best_key
,
352 vigenere_decipher(message
, best_key
))[:50]))
353 return best_key
, best_fit
355 def beaufort_frequency_break(message
, fitness
=Pletters
):
356 """Breaks a Beaufort cipher with frequency analysis
358 >>> beaufort_frequency_break(beaufort_encipher(sanitise("It is time to " \
359 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
360 "afternoon when he left his jacket hanging on the easel in the " \
361 "attic. I jump every time I hear a footstep on the stairs, " \
362 "certain that the theft has been discovered and that I will " \
363 "be caught. The SS officer visits less often now " \
364 "that he is sure"), 'florence')) # doctest: +ELLIPSIS
365 ('florence', -307.5473096791...)
367 best_fit
= float("-inf")
369 sanitised_message
= sanitise(message
)
370 for trial_length
in range(1, 20):
371 splits
= every_nth(sanitised_message
, trial_length
)
372 key
= ''.join([chr(-caesar_break(s
)[0] % 26 + ord('a')) for s
in splits
])
373 plaintext
= beaufort_decipher(sanitised_message
, key
)
374 fit
= fitness(plaintext
)
375 logger
.debug('Beaufort key length of {0} ({1}) gives fit of {2}'.
376 format(trial_length
, key
, fit
))
380 logger
.info('Beaufort break best fit with key {0} gives fit '
381 'of {1} and decrypt starting: {2}'.format(best_key
,
383 beaufort_decipher(message
, best_key
))[:50]))
384 return best_key
, best_fit
388 def plot_frequency_histogram(freqs
, sort_key
=None):
389 x
= range(len(freqs
.keys()))
390 y
= [freqs
[l
] for l
in sorted(freqs
.keys(), key
=sort_key
)]
392 ax
= f
.add_axes([0.1, 0.1, 0.9, 0.9])
393 ax
.bar(x
, y
, align
='center')
395 ax
.set_xticklabels(sorted(freqs
.keys(), key
=sort_key
))
399 if __name__
== "__main__":