Bits of tinkering
[cipher-training.git] / slides / caesar-break.html
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>Breaking caesar ciphers</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
6 <style type="text/css">
7 /* Slideshow styles */
8 body {
9 font-size: 20px;
10 }
11 h1, h2, h3 {
12 font-weight: 400;
13 margin-bottom: 0;
14 }
15 h1 { font-size: 3em; }
16 h2 { font-size: 2em; }
17 h3 { font-size: 1.6em; }
18 a, a > code {
19 text-decoration: none;
20 }
21 code {
22 -moz-border-radius: 5px;
23 -web-border-radius: 5px;
24 background: #e7e8e2;
25 border-radius: 5px;
26 font-size: 16px;
27 }
28 .plaintext {
29 background: #272822;
30 color: #80ff80;
31 text-shadow: 0 0 20px #333;
32 padding: 2px 5px;
33 }
34 .ciphertext {
35 background: #272822;
36 color: #ff6666;
37 text-shadow: 0 0 20px #333;
38 padding: 2px 5px;
39 }
40 .indexlink {
41 position: absolute;
42 bottom: 1em;
43 left: 1em;
44 }
45 .float-right {
46 float: right;
47 }
48 </style>
49 </head>
50 <body>
51 <textarea id="source">
52
53 # Breaking caesar ciphers
54
55 ![center-aligned Caesar wheel](caesarwheel1.gif)
56
57 ---
58
59 layout: true
60
61 .indexlink[[Index](index.html)]
62
63 ---
64
65 # Human vs Machine
66
67 Slow but clever vs Dumb but fast
68
69 ## Human approach
70
71 Ciphertext | Plaintext
72 ---|---
73 ![left-aligned Ciphertext frequencies](c1a_frequency_histogram.png) | ![left-aligned English frequencies](english_frequency_histogram.png)
74
75 ---
76
77 # Human vs machine
78
79 ## Machine approach
80
81 Brute force.
82
83 Try all keys.
84
85 * How many keys to try?
86
87 ## Basic idea
88
89 ```
90 for each key:
91 decipher with this key
92 how close is it to English?
93 remember the best key
94 ```
95
96 What steps do we know how to do?
97
98 ---
99 # How close is it to English?
100
101 What does English look like?
102
103 * We need a model of English.
104
105 How do we define "closeness"?
106
107 ## Here begineth the yak shaving
108
109 ---
110
111 # What does English look like?
112
113 ## Abstraction: frequency of letter counts
114
115 Letter | Count
116 -------|------
117 a | 489107
118 b | 92647
119 c | 140497
120 d | 267381
121 e | 756288
122 . | .
123 . | .
124 . | .
125 z | 3575
126
127 Use this to predict the probability of each letter, and hence the probability of a sequence of letters.
128
129 ---
130
131 .float-right[![right-aligned Typing monkey](typingmonkeylarge.jpg)]
132
133 # Naive Bayes, or the bag of letters
134
135 What is the probability that this string of letters is a sample of English?
136
137 Ignore letter order, just treat each letter individually.
138
139 Probability of a text is `\( \prod_i p_i \)`
140
141 Letter | h | e | l | l | o | hello
142 ------------|---------|---------|---------|---------|---------|-------
143 Probability | 0.06645 | 0.12099 | 0.04134 | 0.04134 | 0.08052 | 1.10648239 × 10<sup>-6</sup>
144
145 Letter | i | f | m | m | p | ifmmp
146 ------------|---------|---------|---------|---------|---------|-------
147 Probability | 0.06723 | 0.02159 | 0.02748 | 0.02748 | 0.01607 | 1.76244520 × 10<sup>-8</sup>
148
149 (Implmentation issue: this can often underflow, so get in the habit of rephrasing it as `\( \sum_i \log p_i \)`)
150
151 Letter | h | e | l | l | o | hello
152 ------------|---------|---------|---------|---------|---------|-------
153 Probability | -1.1774 | -0.9172 | -1.3836 | -1.3836 | -1.0940 | -5.956055
154
155
156 ---
157
158 # Frequencies of English
159
160 But before then how do we count the letters?
161
162 * Read a file into a string
163 ```python
164 open()
165 .read()
166 ```
167 * Count them
168 ```python
169 import collections
170 collections.Counter()
171 ```
172
173 Create the `language_models.py` file for this.
174
175 ---
176
177 # Canonical forms
178
179 Counting letters in _War and Peace_ gives all manner of junk.
180
181 * Convert the text in canonical form (lower case, accents removed, non-letters stripped) before counting
182
183 ```python
184 [l.lower() for l in text if ...]
185 ```
186 ---
187
188 # Accents
189
190 ```python
191 >>> 'é' in string.ascii_letters
192 >>> 'e' in string.ascii_letters
193 ```
194
195 ## Unicode, combining codepoints, and normal forms
196
197 Text encodings will bite you when you least expect it.
198
199 - **é** : LATIN SMALL LETTER E WITH ACUTE (U+00E9)
200
201 - **e** + **&nbsp;&#x301;** : LATIN SMALL LETTER E (U+0065) + COMBINING ACUTE ACCENT (U+0301)
202
203 * urlencoding is the other pain point.
204
205 ---
206
207 # Five minutes on StackOverflow later...
208
209 ```python
210 import unicodedata
211
212 def unaccent(text):
213 """Remove all accents from letters.
214 It does this by converting the unicode string to decomposed compatibility
215 form, dropping all the combining accents, then re-encoding the bytes.
216
217 >>> unaccent('hello')
218 'hello'
219 >>> unaccent('HELLO')
220 'HELLO'
221 >>> unaccent('héllo')
222 'hello'
223 >>> unaccent('héllö')
224 'hello'
225 >>> unaccent('HÉLLÖ')
226 'HELLO'
227 """
228 return unicodedata.normalize('NFKD', text).\
229 encode('ascii', 'ignore').\
230 decode('utf-8')
231 ```
232
233 ---
234
235 # Find the frequencies of letters in English
236
237 1. Read from `shakespeare.txt`, `sherlock-holmes.txt`, and `war-and-peace.txt`.
238 2. Find the frequencies (`.update()`)
239 3. Sort by count (read the docs...)
240 4. Write counts to `count_1l.txt`
241 ```python
242 with open('count_1l.txt', 'w') as f:
243 for each letter...:
244 f.write('text\t{}\n'.format(count))
245 ```
246
247 ---
248
249 # Reading letter probabilities
250
251 1. Load the file `count_1l.txt` into a dict, with letters as keys.
252
253 2. Normalise the counts (components of vector sum to 1): `$$ \hat{\mathbf{x}} = \frac{\mathbf{x}}{\| \mathbf{x} \|} = \frac{\mathbf{x}}{ \mathbf{x}_1 + \mathbf{x}_2 + \mathbf{x}_3 + \dots }$$`
254 * Return a new dict
255 * Remember the doctest!
256
257 3. Create a dict `Pl` that gives the log probability of a letter
258
259 4. Create a function `Pletters` that gives the probability of an iterable of letters
260 * What preconditions should this function have?
261 * Remember the doctest!
262
263 ---
264
265 # Breaking caesar ciphers
266
267 New file: `cipherbreak.py`
268
269 ## Remember the basic idea
270
271 ```
272 for each key:
273 decipher with this key
274 how close is it to English?
275 remember the best key
276 ```
277
278 Try it on the text in `2013/1a.ciphertext`. Does it work?
279
280 ---
281
282 # Aside: Logging
283
284 Better than scattering `print()`statements through your code
285
286 ```python
287 import logging
288
289 logger = logging.getLogger(__name__)
290 logger.addHandler(logging.FileHandler('cipher.log'))
291 logger.setLevel(logging.WARNING)
292
293 logger.debug('Caesar break attempt using key {0} gives fit of {1} '
294 'and decrypt starting: {2}'.format(shift, fit, plaintext[:50]))
295
296 ```
297 * Yes, it's ugly.
298
299 Use `logger.setLevel()` to change the level: CRITICAL, ERROR, WARNING, INFO, DEBUG
300
301 Use `logger.debug()`, `logger.info()`, etc. to log a message.
302
303 ---
304
305 # Homework: how much ciphertext do we need?
306
307 ## Let's do an experiment to find out
308
309 1. Load the whole corpus into a string (sanitised)
310 2. Select a random chunk of plaintext and a random key
311 3. Encipher the text
312 4. Score 1 point if `caesar_cipher_break()` recovers the correct key
313 5. Repeat many times and with many plaintext lengths
314
315 ```python
316 import csv
317
318 def show_results():
319 with open('caesar_break_parameter_trials.csv', 'w') as f:
320 writer = csv.DictWriter(f, ['name'] + message_lengths,
321 quoting=csv.QUOTE_NONNUMERIC)
322 writer.writeheader()
323 for scoring in sorted(scores.keys()):
324 scores[scoring]['name'] = scoring
325 writer.writerow(scores[scoring])
326 ```
327
328 </textarea>
329 <script src="http://gnab.github.io/remark/downloads/remark-0.6.0.min.js" type="text/javascript">
330 </script>
331
332 <script type="text/javascript"
333 src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&delayStartupUntil=configured"></script>
334
335 <script type="text/javascript">
336 var slideshow = remark.create({ ratio: "16:9" });
337
338 // Setup MathJax
339 MathJax.Hub.Config({
340 tex2jax: {
341 skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
342 }
343 });
344 MathJax.Hub.Queue(function() {
345 $(MathJax.Hub.getAllJax()).map(function(index, elem) {
346 return(elem.SourceElement());
347 }).parent().addClass('has-jax');
348 });
349 MathJax.Hub.Configured();
350 </script>
351 </body>
352 </html>