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', 1), \
135 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
136 (('elephant', 1), -52.834575011...)
139 best_wrap_alphabet
= True
140 best_fit
= float("-inf")
141 for wrap_alphabet
in range(3):
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', 1), \
166 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
167 (('elephant', 1), -52.834575011...)
170 helper_args
= [(message
, word
, wrap
, fitness
)
171 for word
in wordlist
for wrap
in range(3)]
172 # Gotcha: the helper function here needs to be defined at the top level
173 # (limitation of Pool.starmap)
174 breaks
= pool
.starmap(keyword_break_worker
, helper_args
, chunksize
)
175 return max(breaks
, key
=lambda k
: k
[1])
177 def keyword_break_worker(message
, keyword
, wrap_alphabet
, fitness
):
178 plaintext
= keyword_decipher(message
, keyword
, wrap_alphabet
)
179 fit
= fitness(plaintext
)
180 logger
.debug('Keyword break attempt using key {0} (wrap={1}) gives fit of '
181 '{2} and decrypt starting: {3}'.format(keyword
,
182 wrap_alphabet
, fit
, sanitise(plaintext
)[:50]))
183 return (keyword
, wrap_alphabet
), fit
185 def scytale_break(message
, fitness
=Pbigrams
):
186 """Breaks a Scytale cipher
188 >>> scytale_break('tfeulchtrtteehwahsdehneoifeayfsondmwpltmaoalhikotoere' \
189 'dcweatehiplwxsnhooacgorrcrcraotohsgullasenylrendaianeplscdriioto' \
190 'aek') # doctest: +ELLIPSIS
191 (6, -281.276219108...)
194 best_fit
= float("-inf")
195 for key
in range(1, 20):
196 if len(message
) % key
== 0:
197 plaintext
= scytale_decipher(message
, key
)
198 fit
= fitness(sanitise(plaintext
))
199 logger
.debug('Scytale break attempt using key {0} gives fit of '
200 '{1} and decrypt starting: {2}'.format(key
,
201 fit
, sanitise(plaintext
)[:50]))
205 logger
.info('Scytale break best fit with key {0} gives fit of {1} and '
206 'decrypt starting: {2}'.format(best_key
, best_fit
,
207 sanitise(scytale_decipher(message
, best_key
))[:50]))
208 return best_key
, best_fit
211 def column_transposition_break_mp(message
, translist
=transpositions
,
212 fitness
=Pbigrams
, chunksize
=500):
213 """Breaks a column transposition cipher using a dictionary and
214 n-gram frequency analysis
216 # >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
217 # "It is a truth universally acknowledged, that a single man in \
218 # possession of a good fortune, must be in want of a wife. However \
219 # little known the feelings or views of such a man may be on his \
220 # first entering a neighbourhood, this truth is so well fixed in the \
221 # minds of the surrounding families, that he is considered the \
222 # rightful property of some one or other of their daughters."), \
224 # translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
225 # (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
226 # (6, 1, 0, 4, 5, 3, 2): ['keyword']}) # doctest: +ELLIPSIS
227 # (((2, 0, 5, 3, 1, 4, 6), False), 0.0628106372...)
228 # >>> column_transposition_break_mp(column_transposition_encipher(sanitise( \
229 # "It is a truth universally acknowledged, that a single man in \
230 # possession of a good fortune, must be in want of a wife. However \
231 # little known the feelings or views of such a man may be on his \
232 # first entering a neighbourhood, this truth is so well fixed in the \
233 # minds of the surrounding families, that he is considered the \
234 # rightful property of some one or other of their daughters."), \
236 # translist={(2, 0, 5, 3, 1, 4, 6): ['encipher'], \
237 # (5, 0, 6, 1, 3, 4, 2): ['fourteen'], \
238 # (6, 1, 0, 4, 5, 3, 2): ['keyword']}, \
239 # target_counts=normalised_english_trigram_counts) # doctest: +ELLIPSIS
240 # (((2, 0, 5, 3, 1, 4, 6), False), 0.0592259560...)
243 helper_args
= [(message
, trans
, columnwise
, fitness
)
244 for trans
in translist
.keys()
245 for columnwise
in [True, False]]
246 # Gotcha: the helper function here needs to be defined at the top level
247 # (limitation of Pool.starmap)
248 breaks
= pool
.starmap(column_transposition_break_worker
,
249 helper_args
, chunksize
)
250 return max(breaks
, key
=lambda k
: k
[1])
251 column_transposition_break
= column_transposition_break_mp
253 def column_transposition_break_worker(message
, transposition
, columnwise
,
255 plaintext
= column_transposition_decipher(message
, transposition
, columnwise
=columnwise
)
256 fit
= fitness(sanitise(plaintext
))
257 logger
.debug('Column transposition break attempt using key {0} '
258 'gives fit of {1} and decrypt starting: {2}'.format(
260 sanitise(plaintext
)[:50]))
261 return (transposition
, columnwise
), fit
264 def transposition_break_exhaustive(message
, fitness
=Pbigrams
):
265 best_transposition
= ''
266 best_pw
= float('-inf')
267 for keylength
in range(1, 21):
268 if len(message
) % keylength
== 0:
269 for transposition
in permutations(range(keylength
)):
270 for columnwise
in [True, False]:
271 plaintext
= column_transposition_decipher(message
,
272 transposition
, columnwise
=columnwise
)
273 fit
=fitness(plaintext
)
274 logger
.debug('Column transposition break attempt using key {0} {1} '
275 'gives fit of {2} and decrypt starting: {3}'.format(
276 transposition
, columnwise
, pw
,
277 sanitise(plaintext
)[:50]))
279 best_transposition
= transposition
280 best_columnwise
= columnwise
282 return (best_transposition
, best_columnwise
), best_pw
285 def vigenere_keyword_break(message
, wordlist
=keywords
, fitness
=Pletters
):
286 """Breaks a vigenere cipher using a dictionary and
289 >>> vigenere_keyword_break(vigenere_encipher(sanitise('this is a test ' \
290 'message for the vigenere decipherment'), 'cat'), \
291 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
292 ('cat', -52.947271216...)
295 best_fit
= float("-inf")
296 for keyword
in wordlist
:
297 plaintext
= vigenere_decipher(message
, keyword
)
298 fit
= fitness(plaintext
)
299 logger
.debug('Vigenere break attempt using key {0} '
300 'gives fit of {1} and decrypt starting: {2}'.format(
302 sanitise(plaintext
)[:50]))
305 best_keyword
= keyword
306 logger
.info('Vigenere break best fit with key {0} gives fit '
307 'of {1} and decrypt starting: {2}'.format(best_keyword
,
309 vigenere_decipher(message
, best_keyword
))[:50]))
310 return best_keyword
, best_fit
312 def vigenere_keyword_break_mp(message
, wordlist
=keywords
, fitness
=Pletters
,
314 """Breaks a vigenere cipher using a dictionary and
317 >>> vigenere_keyword_break_mp(vigenere_encipher(sanitise('this is a test ' \
318 'message for the vigenere decipherment'), 'cat'), \
319 wordlist=['cat', 'elephant', 'kangaroo']) # doctest: +ELLIPSIS
320 ('cat', -52.947271216...)
323 helper_args
= [(message
, word
, fitness
)
324 for word
in wordlist
]
325 # Gotcha: the helper function here needs to be defined at the top level
326 # (limitation of Pool.starmap)
327 breaks
= pool
.starmap(vigenere_keyword_break_worker
, helper_args
, chunksize
)
328 return max(breaks
, key
=lambda k
: k
[1])
330 def vigenere_keyword_break_worker(message
, keyword
, fitness
):
331 plaintext
= vigenere_decipher(message
, keyword
)
332 fit
= fitness(plaintext
)
333 logger
.debug('Vigenere keyword break attempt using key {0} gives fit of '
334 '{1} and decrypt starting: {2}'.format(keyword
,
335 fit
, sanitise(plaintext
)[:50]))
340 def vigenere_frequency_break(message
, fitness
=Pletters
):
341 """Breaks a Vigenere cipher with frequency analysis
343 >>> vigenere_frequency_break(vigenere_encipher(sanitise("It is time to " \
344 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
345 "afternoon when he left his jacket hanging on the easel in the " \
346 "attic. I jump every time I hear a footstep on the stairs, " \
347 "certain that the theft has been discovered and that I will " \
348 "be caught. The SS officer visits less often now that he is " \
349 "sure"), 'florence')) # doctest: +ELLIPSIS
350 ('florence', -307.5473096791...)
352 best_fit
= float("-inf")
354 sanitised_message
= sanitise(message
)
355 for trial_length
in range(1, 20):
356 splits
= every_nth(sanitised_message
, trial_length
)
357 key
= ''.join([chr(caesar_break(s
)[0] + ord('a')) for s
in splits
])
358 plaintext
= vigenere_decipher(sanitised_message
, key
)
359 fit
= fitness(plaintext
)
360 logger
.debug('Vigenere key length of {0} ({1}) gives fit of {2}'.
361 format(trial_length
, key
, fit
))
365 logger
.info('Vigenere break best fit with key {0} gives fit '
366 'of {1} and decrypt starting: {2}'.format(best_key
,
368 vigenere_decipher(message
, best_key
))[:50]))
369 return best_key
, best_fit
371 def beaufort_frequency_break(message
, fitness
=Pletters
):
372 """Breaks a Beaufort cipher with frequency analysis
374 >>> beaufort_frequency_break(beaufort_encipher(sanitise("It is time to " \
375 "run. She is ready and so am I. I stole Daniel's pocketbook this " \
376 "afternoon when he left his jacket hanging on the easel in the " \
377 "attic. I jump every time I hear a footstep on the stairs, " \
378 "certain that the theft has been discovered and that I will " \
379 "be caught. The SS officer visits less often now " \
380 "that he is sure"), 'florence')) # doctest: +ELLIPSIS
381 ('florence', -307.5473096791...)
383 best_fit
= float("-inf")
385 sanitised_message
= sanitise(message
)
386 for trial_length
in range(1, 20):
387 splits
= every_nth(sanitised_message
, trial_length
)
388 key
= ''.join([chr(-caesar_break(s
)[0] % 26 + ord('a')) for s
in splits
])
389 plaintext
= beaufort_decipher(sanitised_message
, key
)
390 fit
= fitness(plaintext
)
391 logger
.debug('Beaufort key length of {0} ({1}) gives fit of {2}'.
392 format(trial_length
, key
, fit
))
396 logger
.info('Beaufort break best fit with key {0} gives fit '
397 'of {1} and decrypt starting: {2}'.format(best_key
,
399 beaufort_decipher(message
, best_key
))[:50]))
400 return best_key
, best_fit
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
)]
408 ax
= f
.add_axes([0.1, 0.1, 0.9, 0.9])
409 ax
.bar(x
, y
, align
='center')
411 ax
.set_xticklabels(sorted(freqs
.keys(), key
=sort_key
))
415 if __name__
== "__main__":