Updated for challenge 9
[cipher-tools.git] / 2019 / 2019-challenge5.ipynb
1 {
2 "cells": [
3 {
4 "cell_type": "code",
5 "execution_count": 1,
6 "metadata": {},
7 "outputs": [],
8 "source": [
9 "import os,sys,inspect\n",
10 "currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n",
11 "parentdir = os.path.dirname(currentdir)\n",
12 "sys.path.insert(0,parentdir) "
13 ]
14 },
15 {
16 "cell_type": "code",
17 "execution_count": 2,
18 "metadata": {},
19 "outputs": [],
20 "source": [
21 "from cipher.caesar import *\n",
22 "from cipher.affine import *\n",
23 "from cipher.keyword_cipher import *\n",
24 "from cipher.column_transposition import *\n",
25 "from cipher.vigenere import *\n",
26 "from support.text_prettify import *\n",
27 "from support.utilities import *\n",
28 "from support.plot_frequency_histogram import *"
29 ]
30 },
31 {
32 "cell_type": "code",
33 "execution_count": 18,
34 "metadata": {},
35 "outputs": [],
36 "source": [
37 "challenge_number = 5\n",
38 "plaintext_a_filename = f'{challenge_number}a.plaintext'\n",
39 "plaintext_b_filename = f'{challenge_number}b.plaintext'\n",
40 "ciphertext_a_filename = f'{challenge_number}a.ciphertext'\n",
41 "ciphertext_b_filename = f'{challenge_number}b.ciphertext'"
42 ]
43 },
44 {
45 "cell_type": "code",
46 "execution_count": 43,
47 "metadata": {},
48 "outputs": [],
49 "source": [
50 "ca = open(ciphertext_a_filename).read()\n",
51 "cb = open(ciphertext_b_filename).read()\n",
52 "sca = sanitise(ca)\n",
53 "pca = letters(ca)\n",
54 "pta = depunctuate(ca)\n",
55 "\n",
56 "scb = sanitise(cb)\n",
57 "pcb = letters(cb)\n",
58 "ptb = depunctuate(cb)\n",
59 "\n",
60 "rcb = cat(reversed(cb))\n",
61 "rscb = sanitise(rcb)\n",
62 "ptrb = depunctuate(rcb)"
63 ]
64 },
65 {
66 "cell_type": "code",
67 "execution_count": 62,
68 "metadata": {},
69 "outputs": [
70 {
71 "data": {
72 "text/plain": [
73 "('solar', <KeywordWrapAlphabet.from_last: 2>, -2436.5996155834796)"
74 ]
75 },
76 "execution_count": 62,
77 "metadata": {},
78 "output_type": "execute_result"
79 }
80 ],
81 "source": [
82 "(key_a, wrap_a), score_a = keyword_break_mp(sca)\n",
83 "key_a, wrap_a, score_a"
84 ]
85 },
86 {
87 "cell_type": "code",
88 "execution_count": 63,
89 "metadata": {},
90 "outputs": [
91 {
92 "name": "stdout",
93 "output_type": "stream",
94 "text": [
95 "harry mike has turned out to be really useful following his report to you about the apollo xine arm\n",
96 "is she has turned up a number of other computer reports hinting at possible sabotage attempts on\n",
97 "viii through xii some of them we already knew about the guidance problems with apollo x and the\n",
98 "programme alarms and descent trajectory problems on xi but he also showed me some files from the\n",
99 "building and maintenance logs for the future apollo fleet and pointed out some worrying lapses in\n",
100 "particular there is a gap in the records of the apollo xiii service modules owe are running a few\n",
101 "checks before assembly to make sure everything is okay before launch my first instinct was to place\n",
102 "everything on hold while we tracked down the saboteur but the whole building launch process is a\n",
103 "fine tuned machine and i am worried that if we disrupt it then we might cause more problems in\n",
104 "particular it will be easier to detect unexpected behaviour if we know exactly what to expect mike\n",
105 "is really worried that the soviets could have infiltrated the program he has never for given them\n",
106 "for the death of his son who was shot down by a mig over the korean peninsula i am hoping that his\n",
107 "grief will drive him to help us get to the bottom of this mystery for now we have another problem my\n",
108 "team at langley were tipped off by a journalist at the newyork post about an encrypted letter sent\n",
109 "to the newsdesk there it came with a cover note which said that the cipher key would be published in\n",
110 "the wanted ads but there area lot of those spread over hundreds of newspapers and the editor didnt\n",
111 "want to devote hours of staff time to tracking down the advert i think he assumed it was just\n",
112 "another crackpot attention seeker but justin case he asked the journalist to try breaking the cipher\n",
113 "herself she recognised it as avi genere cipher but it came with a little twist that she could not\n",
114 "figure out so she sent it to someone she knew in the cia once they cracked it they realised what it\n",
115 "was and sent it on to me the letter contains details of some of the events we have been\n",
116 "investigating and blames the soviets for them it would have been dynamite if it had been published\n",
117 "so it is just as well we were able to stop it at source the journalist was persuaded to tell her\n",
118 "boss that the cipher couldnt be cracked but in exchange we owe her an exclusive at the end of all of\n",
119 "this all the best meg\n"
120 ]
121 }
122 ],
123 "source": [
124 "print(lcat(tpack(segment(keyword_decipher(sca, key_a, wrap_a)))))"
125 ]
126 },
127 {
128 "cell_type": "code",
129 "execution_count": 42,
130 "metadata": {},
131 "outputs": [
132 {
133 "data": {
134 "text/plain": [
135 "2373"
136 ]
137 },
138 "execution_count": 42,
139 "metadata": {},
140 "output_type": "execute_result"
141 }
142 ],
143 "source": [
144 "open(plaintext_a_filename, 'w').write(lcat(tpack(segment(keyword_decipher(sca, key_a, wrap_a)))))"
145 ]
146 },
147 {
148 "cell_type": "code",
149 "execution_count": 64,
150 "metadata": {},
151 "outputs": [
152 {
153 "name": "stdout",
154 "output_type": "stream",
155 "text": [
156 "zodiac \n",
157 "\n",
158 "totheeditorofthenewyorkposttheheadlineofthisstorywritesitselfthesovietshaveinfiltratedourspaceagencynasaandhaveactivelyembarkedonaprogrammeofsabotageaimedatkillingourastronautsanddestroyingourmissionnotcontentwithsupportingwaracrossthefareastandfomentingrevolutionacrosstheamericastheyarenowcampedinourbackyardincubaandhavetaunteduswiththeirownspaceprogrammenowtheyhavelaunchedanattackontheheartofourcountryinanattempttodestroyourmoraleandtoreasserttheirdominanceinspacenopartofthelunarprogrammehasbeenunaffectedbytheiragentsthereareconstantleaksofourtechnologytotheengineersatbaikonurandourplansarelaidbaretoaidtheussrinitseffortstoovertakeusourbraveastronautshavebeenrepeatedlyplacedinharmswayanditisonlybecauseoftheeffectivenessofoursecurityagenciesandthebraveryandskillofourastronautsthatnoonehasbeenkilledinspacesofaritisonlyamatteroftimebeforeourenemiessucceedourpoliticalmastersdonotwantyoutoknowthattheapolloxlunarmoduleguidanceprogrammewascorruptedbysovietagentsorthattheapolloxiastronautswerealmostkilledbyacollisionwiththeirownservicemoduleastheyreenteredtheearthsatmospherethesebraveastronautscouldhavebeenkilledbytheactionsofsovietoperatorswhohadinfiltratedtheprogrammingandengineeringteamsourpoliticianswantyoutothinkthatapolloxiiwasstruckbylightningduringitslaunchandthatitwasthisthattookoutthecontrolcircuitrybutaskyourselfwhywouldamachineasadvancedasthesaturnvbevulnerabletoanaturalphenomenonascommonaslightningonthefloridapeninsulaandhowlikelyisittohavebeenstrucktwiceclearlysomeonesetouttosabotagethislaunchjustastheytriedtosabotageboththeapolloxreconnaissanceandtheapolloximoonlandingandreentrythesearepowerfulenemiesabletostrikeatanyaspectoftheapolloprogrammeandonlyastrongresponsefromourgovernmenthasanyhopeofstoppingthemforthesakeofourastronautsandofournationalprideiurgethepresidenttothreatenthestrongestpossibleretaliationiffurtherattacksarelaunchedagainstus\n"
159 ]
160 }
161 ],
162 "source": [
163 "k_a, score_a = vigenere_frequency_break(rscb)\n",
164 "print(k_a, '\\n')\n",
165 "rpb = vigenere_decipher(rscb, k_a)\n",
166 "print(rpb)"
167 ]
168 },
169 {
170 "cell_type": "code",
171 "execution_count": 65,
172 "metadata": {},
173 "outputs": [
174 {
175 "name": "stdout",
176 "output_type": "stream",
177 "text": [
178 "\n",
179 "To the editor of the New York Post:\n",
180 "\n",
181 "The headline of this story writes itself: The Soviets have infiltrated our space agency NASA and have actively embarked on a programme of sabotage, aimed at killing our astronauts and destroying our mission. Not content with supporting war across the Far East and fomenting revolution across the Americas, they are now camped in our backyard in Cuba and have taunted us with their own space programme. Now they have launched an attack on the heart of our country in an attempt to destroy our morale and to reassert their dominance in space.\n",
182 "\n",
183 "No part of the lunar programme has been unaffected by their agents. There are constant leaks of our technology to the engineers at Baikonur, and our plans are laid bare to aid the USSR in its efforts to overtake us. Our brave astronauts have been repeatedly placed in harm’s way and it is only because of the effectiveness of our security agencies and the bravery and skill of our astronauts that no one has been killed in space so far. It is only a matter of time before our enemies succeed.\n",
184 "\n",
185 "Our political masters do not want you to know that the Apollo X lunar module guidance programme was corrupted by Soviet agents or that the Apollo XI astronauts were almost killed by a collision with their own service module as they re-entered the earth’s atmosphere. These brave astronauts could have been killed by the actions of Soviet operators who had infiltrated the programming and engineering teams. Our politicians want you to think that Apollo XII was struck by lightning during its launch and that it was this that took out the control circuitry. But ask yourself, why would a machine as advanced as the Saturn V be vulnerable to a natural phenomenon as common as lightning on the Florida Peninsula? And how likely is it to have been struck twice? Clearly someone set out to sabotage this launch just as they tried to sabotage both the Apollo X reconnaissance and the Apollo XI moon landing and re-entry.\n",
186 "\n",
187 "These are powerful enemies able to strike at any aspect of the Apollo programme and only a strong response from our government has any hope of stopping them.\n",
188 "\n",
189 "For the sake of our astronauts and of our national pride I urge the President to threaten the strongest possible retaliation if further attacks are launched against us.\n"
190 ]
191 }
192 ],
193 "source": [
194 "print(repunctuate(rpb, ptrb))"
195 ]
196 },
197 {
198 "cell_type": "code",
199 "execution_count": 58,
200 "metadata": {},
201 "outputs": [
202 {
203 "data": {
204 "text/plain": [
205 "2317"
206 ]
207 },
208 "execution_count": 58,
209 "metadata": {},
210 "output_type": "execute_result"
211 }
212 ],
213 "source": [
214 "open(plaintext_b_filename, 'w').write(repunctuate(rpb, ptrb))"
215 ]
216 },
217 {
218 "cell_type": "code",
219 "execution_count": null,
220 "metadata": {},
221 "outputs": [],
222 "source": []
223 }
224 ],
225 "metadata": {
226 "kernelspec": {
227 "display_name": "Python 3",
228 "language": "python",
229 "name": "python3"
230 },
231 "language_info": {
232 "codemirror_mode": {
233 "name": "ipython",
234 "version": 3
235 },
236 "file_extension": ".py",
237 "mimetype": "text/x-python",
238 "name": "python",
239 "nbconvert_exporter": "python",
240 "pygments_lexer": "ipython3",
241 "version": "3.7.4"
242 }
243 },
244 "nbformat": 4,
245 "nbformat_minor": 4
246 }