Done challenge 9
[cipher-challenge.git] / 2021 / 2021-challenge5.ipynb
1 {
2 "cells": [
3 {
4 "cell_type": "code",
5 "execution_count": 27,
6 "id": "5c19999b",
7 "metadata": {
8 "Collapsed": "false"
9 },
10 "outputs": [],
11 "source": [
12 "from szyfrow.caesar import *\n",
13 "from szyfrow.affine import *\n",
14 "from szyfrow.keyword_cipher import *\n",
15 "from szyfrow.column_transposition import *\n",
16 "from szyfrow.railfence import *\n",
17 "from szyfrow.support.text_prettify import *\n",
18 "\n",
19 "import numpy as np\n",
20 "import pandas as pd\n",
21 "import matplotlib.pyplot as plt\n",
22 "\n",
23 "import collections\n",
24 "%matplotlib inline"
25 ]
26 },
27 {
28 "cell_type": "code",
29 "execution_count": 2,
30 "id": "d9dd1b5e",
31 "metadata": {
32 "Collapsed": "false"
33 },
34 "outputs": [],
35 "source": [
36 "challenge_number = 5\n",
37 "plaintext_a_filename = f'plaintext.{challenge_number}a.txt'\n",
38 "plaintext_b_filename = f'plaintext.{challenge_number}b.txt'\n",
39 "ciphertext_a_filename = f'ciphertext.{challenge_number}a.txt'\n",
40 "ciphertext_b_filename = f'ciphertext.{challenge_number}b.txt'"
41 ]
42 },
43 {
44 "cell_type": "code",
45 "execution_count": 5,
46 "id": "0f1f792a",
47 "metadata": {
48 "Collapsed": "false"
49 },
50 "outputs": [],
51 "source": [
52 "ca = open(ciphertext_a_filename).read()\n",
53 "cb = open(ciphertext_b_filename).read()\n",
54 "\n",
55 "sca = sanitise(ca)\n",
56 "rsca = cat(reversed(sca))\n",
57 "scb = sanitise(cb)"
58 ]
59 },
60 {
61 "cell_type": "code",
62 "execution_count": 14,
63 "id": "b8d5f9ec-27f1-498b-8e64-c5eb2424e581",
64 "metadata": {},
65 "outputs": [
66 {
67 "data": {
68 "text/plain": [
69 "Counter({'j': 2,\n",
70 " 'n': 145,\n",
71 " 'o': 133,\n",
72 " 'c': 61,\n",
73 " 't': 202,\n",
74 " 'h': 106,\n",
75 " 'l': 74,\n",
76 " 'b': 25,\n",
77 " 'i': 152,\n",
78 " 'w': 44,\n",
79 " 'e': 241,\n",
80 " 'v': 20,\n",
81 " 's': 101,\n",
82 " 'r': 94,\n",
83 " 'a': 162,\n",
84 " 'm': 36,\n",
85 " 'u': 60,\n",
86 " 'g': 48,\n",
87 " 'y': 35,\n",
88 " 'd': 67,\n",
89 " 'f': 35,\n",
90 " 'k': 17,\n",
91 " 'p': 18,\n",
92 " 'x': 4,\n",
93 " 'z': 1})"
94 ]
95 },
96 "execution_count": 14,
97 "metadata": {},
98 "output_type": "execute_result"
99 }
100 ],
101 "source": [
102 "sca_counts = collections.Counter(sca)\n",
103 "sca_counts"
104 ]
105 },
106 {
107 "cell_type": "code",
108 "execution_count": 21,
109 "id": "b5cabba1-ac75-46ea-ac05-8699cc88d986",
110 "metadata": {},
111 "outputs": [
112 {
113 "data": {
114 "text/plain": [
115 "<AxesSubplot:>"
116 ]
117 },
118 "execution_count": 21,
119 "metadata": {},
120 "output_type": "execute_result"
121 },
122 {
123 "data": {
124 "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAD5CAYAAADcDXXiAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAASZUlEQVR4nO3df7DldV3H8ecLMDQgW2KhDYhLzmZiFskVbaSJsoRyCp3ElhpCM1cNin4DTYU5beGUNmpBoaDkL9xUgkaTcNMBCsQFkV8L48bPlRXWstgaRXZ998f57nC6nHvOuefeu3vvZ5+PmTPnfD/n+/l+3/d7z32dz/n+ODdVhSSpLfvs6QIkSQvPcJekBhnuktQgw12SGmS4S1KDDHdJatDIcE9yZJJPJ9mU5M4kZ3ftb0rypSS3dref7utzXpLNSe5JctJi/gCSpKfKqPPck6wCVlXVLUkOAm4GXg68CvifqvqLGfMfA3wIOB74LuBTwPdW1c7Z1nHIIYfU1NTUPH4MSdr73H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icAr05yH+Nvv/fQ+zmu6KZfDlwyRn0v5MnXO/Te0Dft2laD1llVD4yx3JleBZwM/EVV/VeSVcDvDpqxqv6b3rGd0wY9P8qM3/O+wEpg1PGKNwI/3837EeB1Nd5Xi98GHAd8f1fzfyW5YbbBQudz9Ha9vQD4DuBvk7yyql45pL5fB86g98Vf7wZ+t6qeSLIP8EVgtnD/m10Pquq93bY5c4yf68l1dx8BlqwkP0rvI8knq+obA54/alj/US/oJMcAP07vD3HDmC8MkjyfJw+CXVtVnx+jz/cBL+lb16Zx1jWJJMfRC5vQ24Wycci889qGi21P1Jfk/fR2B97Jk5+wqqp+eUifgXWO8Rp8Pk/+rsZ9LS3p39kkZvxMO4BHutHrsD4XAJfXkBMFRvQ/EHgN8Dv0TnDYf8i80zP/jpKcXlWzHutI8mbgkkG/jyTPWdQMWOrhLu0JSW6vqueNnlPLUXcWy4/QG70/wJNnzvzLHi1sAS3V3TLSnnbjoFPf1IxnAG+jd3rw0E8Hy5Ujd2mAJJuAZ9E702PJHH+QxmW4SwNMuv9cWioMd0lq0JK8QlWSND+GuyQ1yHCXpAYZ7pLUoP8DQ2uGuOCXRZEAAAAASUVORK5CYII=\n",
125 "text/plain": [
126 "<Figure size 432x288 with 1 Axes>"
127 ]
128 },
129 "metadata": {
130 "needs_background": "light"
131 },
132 "output_type": "display_data"
133 }
134 ],
135 "source": [
136 "pd.Series(sca_counts).sort_index().plot.bar()"
137 ]
138 },
139 {
140 "cell_type": "code",
141 "execution_count": 28,
142 "id": "61ce2102-294e-4b1a-842c-1607aa7a4b05",
143 "metadata": {},
144 "outputs": [
145 {
146 "name": "stdout",
147 "output_type": "stream",
148 "text": [
149 "5 \n",
150 "\n",
151 "jodieicanseewhyyouareconcernedbutifindithardtobelievethatagathacouldhavebeenpartofaconspiracyshewasafaithfulcolleagueinallthetimeiworkedwithherandnooneeversuggestedotherwiseofcoursewerantheusualspotchecksfromtimetotimebutnothingunusualwasfoundhavingsaidthatthemessageyoufoundinthearchiveisreallyworryingmyfirstthoughtwasthatshemighthavebeenactingasadoubleagenttryingtodestabilisenaziintelligencebutthatdoesntfitwiththetextitiscrucialtoourmissionthatwemaintainthebalanceofuncertaintyanddirectittoouradvantagemakeitlooklikeshehaddefinitelyhadanotheragendaitrawledthroughmyownrecordstoseeifanyoneelseagathaandiworkedwithmighthavebeeninvolvedihatetosayitbuttheonlypersonofinterestatthemomentischarlieweworkedtogetheronthekohinoortwinscaseandagathawashergreatauntnotthattreacheryisagenetictraitbutinvettingcirclesitcanbetreatedlikeitisinheritedsoisupposeweoughttotakethatseriouslyespeciallysinceshebecameprettyseniorinamericanintelligenceicheckedourcurrentcasefilesandalthoughsheisretiredshestillactsasgovernmentliaisonsheisinlondonatthemomentinthenewembassybuildingwhichwillmakeitdifficulttogetholdofherifshewantstostayhiddenwecantaffordtoupsetouruscousinsandifwearewrongaboutherwemightalsopoisonthewellwhenitcomestointelligenceexchangetheyhaventforgivenusforphilbyandmacleanyetsoicanimaginehowtheywouldreactifitturnsoutthatoneofourownisadoubleagentandhasinfiltratedtheirinnersanctumisentoneoftheelvestotakealookatherapartmentinnewjerseyitwasprettycleanasyoucanimaginebuttheywereabletoliftthefollowingextractitwashardtoreadandevenhardertodeciphersincesheusedavigenereencryptionbutoneincriminatingfeaturestandsoutevenwithoutadecryptsheusedtheadmorseencodingontopofthevigenerecipheriamnotsurewhatweshoulddonextcouldyougettheteamtotakealookatthefilemaybethisisallabigcoincidenceoramisunderstandingifnotthenwemayhavetotelllondonandwashingtonandiamreallynotlookingforwardtothatallthebestharry\n"
152 ]
153 }
154 ],
155 "source": [
156 "key_a, score_a = railfence_break(sca, fitness=Ptrigrams)\n",
157 "print(key_a, '\\n')\n",
158 "pa = railfence_decipher(sca, key_a)\n",
159 "print(pa)"
160 ]
161 },
162 {
163 "cell_type": "code",
164 "execution_count": 26,
165 "id": "605792ee-8bbf-44da-b33f-6bd2321f449e",
166 "metadata": {},
167 "outputs": [
168 {
169 "name": "stdout",
170 "output_type": "stream",
171 "text": [
172 "(0, 1, 2, 3) False True \n",
173 "\n",
174 "sichacnerlliitniyicaiemanorianesletthpemhbecnhseesinrllacpecaeylhioulestkethtatohghtdoewnpossusiredsiirersinhtieodlietaeebethactdleswricstinuevntbutniarnticnnegiyishehcetretahtetnoeuatsgrerehsohawtagabeanhacsgtwiooonckohahtnehernegorkedlowesliefahcsntismometthttsehnteafonsersfylntthetubtesayetetidihivloeninyebefthargimhwitaekrediwiaahtagaesleiyonhafihoseosdrfrecswoyoughdrhtawleirtisendfarelnottdahdtellnifgaddyehseliknooltkeinmegoantedarstooiitcrdirhnaylainireceofudcnaeebaetnirintimewrthaeoisyrmisootrciakrcsutitpetetthtiwtiesntnodtctthtbectigeeletrziitnesnbilrtsetgtosiyrrenteaeltdoursagrctieneeaaveithgphemttahowasehguetthhrifdngmnyrrelywnaertveinhcrotheaidngufoayegiesshehtkthaaiasvvinthdndsfotwlaenushgnianotnubeuotiuemixromiskcetchupsllusuahtnawernsrugofcasiwathehdetsggetsresneeiondleraihtinkedoowimtimdhtlainaaugauolltluftaitfasaosheecarenspecafoartuneeoavehdlurhaceagaethacveifobeydraoditpifihdbutnreecontraunhyyeeeseicawidoeyrrthahebetlltotahldtoeawrnngfakoonnottllaeamrndnaagtosihsnndwcnodslloyetohaveayamaenwgttocgiflidnarstodnupamigoecpidednioobigellayisiotebeematifefattmooloakepotmeeteettenyoucluorextnodddhouiewtgewhfustoamnerehbecinenenevietfoyntongnirncoaesraadmehtdoeuststpnecreatunithtnevuoutodnaoresstaeiinguaniocriiienebutmoithcryeeerngentvadeeuslsecersihhpitodesredenhabvedradaarotsharpawtfactntxetwinwllohtheefililetkaerceywlttubinetamimucadysaeleaiyttesprcwtihrserjweutinaemtaapacehteookgaekntotnevlytheaoencentiimusancarentiriehtdorathlifkasirdnaigengelbiadotinwaouraoenthatatuoaurndtifnactirdloywothtwwnehsgamecanrostoanyolcaiandablivorpvsunhgivoofttaveeyehengeohcxmncedgilantehotsycomeineellwtwehasonuopoetaltgimnerwltuoangatrweswealidniinshuocfuruatesntounrofintadcewtddebhyantosbtnaishetireodofyohtotogslucaiffutiealmatiwhgwhiunidubuihssamwemtnehetinaemoatheoanorlonsisivnshnsiawntlemnrlgoveasthllawtseiedsoitebeisoshgttholadnhlestfescntcorrunourjekc \n"
175 ]
176 }
177 ],
178 "source": [
179 "(word_a, fill_a, empty_a), score_a = column_transposition_break(rsca, fitness=Ptrigrams)\n",
180 "print(word_a, fill_a, empty_a, '\\n')\n",
181 "pa = column_transposition_decipher(rsca, word_a, fillcolumnwise=fill_a, emptycolumnwise=empty_a)\n",
182 "print(pa)"
183 ]
184 },
185 {
186 "cell_type": "code",
187 "execution_count": 16,
188 "id": "c3cccd86-5e40-4040-8f91-9ca53ac6e909",
189 "metadata": {},
190 "outputs": [
191 {
192 "name": "stdout",
193 "output_type": "stream",
194 "text": [
195 "a KeywordWrapAlphabet.from_a \n",
196 "\n",
197 "jnocthltoboiwhelewnvsroaaetmhuugtauasoyotibnbtdinnafhilstalnteuateeyhadmoeetohvvaiooreswtoindaataatigirkhoetasicaynngecaaurhceiedmtblckiehwtnfpsarbestheletnehmeiouisooutnentoeaarnyennbeofgidnrcneepomfteoyeodpgpoalcgaahyscnsanetnanelothroasyuneuitaeiaacueetfpreatflaalmidiadeeetewcurnulhcmiietisaonnsatsgonerirwrmfhushmgeeigultroelsitechttitetsatisawtiaaucnyrcortgilksdflhtediethycreineahwrtmaenohtytensneehmiceedornhnisnawsetotecsgcrtnncstteienesiswtohtulcanecmtsiaaiiehcrucssnogseseatvrlahinoeonhmaidihaefcgtfeeasaewafusucsnaeaowmlonhwemselexehetvnpidaytnmhwoltfnotnrwobnaiftdincutneltkktatneeirtaaaieuwrtleonettrtadadeiicsdnryttniigesatvhurpsdmroiooieihnthtudtoueemelteabiagoeciutnfowmeoodwsoaratofrohteardceyaorbfirbehgalverasahsiulgntiwetrnergehifretssckomtbonulfdiahhsefdhceeyrgitgaaehvetaoenytsieiegetdnthticiomihennbnfeiaitoaneeoihdieaorntlhgoedsfolgaikiihbilieabhlrotstothiwegetoowcagahranhrhieiauviiecealiirdsoehttsoyeliseetermcnlnckurteedhhitdslsontissonhmieesuihwmifuohorhnoydetooerondewguriapoelnotticcgevfiurlncnsaaetwdciruaeundlensiatrenmnehvoeohpmiwstptescmntyeeihlixcwaodehedpseuaeeriuernnaenuettctutdscntfvncemswwodxuotttkotfmesliidemnsditnavtlodhtnmloogwtalbhyiiehrcndiddovtahdanacncsaalouihtokheonsgdtsoswhuptsreoungnwshviteeyuithvalynrthwthtancsdaeigtbnzlibtoswtetrcorotmitecoranditdamkoleantdnaerwruwrsoaysaadewgtenvdtsutyefnttmnalokehhkotaeahegutateyntibetrlabtdtsieupogaeeieplshbpenoeitlcieornflatseietlagmnsnilatetnwsbnwiltiltodistthdcnrttuuiiwrntegtoswlicongnhnyaogsobalaocgnhyratuthooiaegdalrhiraieotetaoeaetjrwsylyuaitealftlwtaahravnrohrsevgecobicaitrdoniaesehaengnteeeraueehoelyteoaoaietilbnioadrigteyaelnnigdalnknadtleteweentethpoyfceerhouoeeeofttuaadmonilistshaagnaalueixuunahetdtvakhiagaontnendheeotpiaerrterstrntrettcneitpukrsyerireedeilhriseontneygldtlfsiadosfohhietieahrfyeiieettfsahtessfslrneacoghbtorseetehinnntuswdheeohrirsndhtklhacrenhhlaniyiras\n"
198 ]
199 }
200 ],
201 "source": [
202 "(word_a, wrap_a), score_a = keyword_break(sca, fitness=Pletters)\n",
203 "print(word_a, wrap_a, '\\n')\n",
204 "pa = keyword_decipher(sca, word_a, wrap_a)\n",
205 "print(pa)"
206 ]
207 },
208 {
209 "cell_type": "code",
210 "execution_count": 11,
211 "id": "47bfce9d-9932-457f-a175-715660ac9d01",
212 "metadata": {},
213 "outputs": [
214 {
215 "name": "stdout",
216 "output_type": "stream",
217 "text": [
218 "okhltfwynjvdgsiuqraecbpxmz \n",
219 "\n",
220 "jiauecdeavaogctdtgiknrassteycppmespsnahaeoviveloiisfcodnesdietpsetthcslyatteackksoaartngeaoilssesseomorbcatesnoushiimtussprcutotlyevdubotcgeifwnsrvtnectdteitcytoaponaapeitieatssrihtiivtafmoliruittwayfetahtalwmwasdumsschnuinsiteisitdaecrasnhpitpoestossupttefwrtsefdssdyolosltttetgupripdcuyooteonsaiinsenmaitrorgryfcpncymttompderatdnoetuceeoetenseonsgeosspuihruaremodbnlfdcetlotechurtoitscgreystiacehetinittcyouttlaricionisgnteaetunmureiiuneetotitnongeacepdusituyenossootcurpunniamntntsekrdscoiataicysolocstfumefttsnstgsfpnpunistsagydaicgtyntdtxtctekiwolsheiycgadefiaeirgavisofeloiupeitdebbeseittoresssotpgredtaiteereslsltoounlirheeioomtnsekcprwnlyraoaaotociecepleapttytdetsvosmatuopeifagytaalgnasrseafracetsrluthsarvforvtcmsdktrsnscnopdmieogteritrmtcofrtennubayevaipdflosccntflcutthrmoemsstcktesatihenototmtelieceouoayoctiiviftosoeasittaoclotsariedcmatlnfadmsoboocvodotsvcdraeneaecogtmteaagusmscrsicrcotospkootutsdoorlnatceenahtdonttetryuidiubprettlccoelndnaieonnaicyottnpocgyofpacarciahlteaatrailtgmproswatdiaeeouumtkfoprdiuinsstegluorpstpildtinosertiyitckatacwyognewetnuyiehttocdoxugsaltctlwntpsttroptriistipteeuepelnuiefkiutynggalxpaeeebaefytndooltyinloeiskedalceiydaamgesdvchootcruilollakesclsisuiunssdapoceabctainmlenangcpwenrtapimignckoetthpoecksdhirecgecesiunlstomevizdoveangeteruaraeyoetuarsiloelsybadtsielistrgrpgrnashnssltgmetiklenpehtfieeyisdabtccbaestsctmpesethieovterdsvelenotpwamsttotwdncvwtiatoeduotarifdsentotedsmyiniodseteignvigodeodealoneecluireeppoogrietmeangdouaimicihsamnavsdsaumichrsepecaaostmlsdrcorsotaetesatstejrgnhdhpsoetsdfedgesscrskiracrntkmtuavousoerlaiostntcstimietttrspttcatdhetasasoteodvioaslromethstdiiomlsdibisledtetgttietecwahfuttrcapatttafeepsslyaiodonencssmissdptoxppiscteleksbcosmsaieitilcttaewostrretrnerierteeuitoewpbrnhtrorttltodcrontaieithmdledfnoslanfaccoteotscrfhtootteefnscetnnfndritsuamcvearnttetcoiiiepnglcttacrornilcebdcsurticcdsiohorsn\n"
221 ]
222 }
223 ],
224 "source": [
225 "word_a, score_a = monoalphabetic_sa_break(sca)\n",
226 "print(word_a, '\\n')\n",
227 "pa = keyword_decipher(sca, word_a)\n",
228 "print(pa)"
229 ]
230 },
231 {
232 "cell_type": "code",
233 "execution_count": 10,
234 "id": "d925f1d9-f70b-4858-85ba-8eb1ae919080",
235 "metadata": {},
236 "outputs": [
237 {
238 "name": "stdout",
239 "output_type": "stream",
240 "text": [
241 "a \n",
242 "\n",
243 "jnocthltoboiwhelewnvsroaaetmhuugtauasoyotibnbtdinnafhilstalnteuateeyhadmoeetohvvaiooreswtoindaataatigirkhoetasicaynngecaaurhceiedmtblckiehwtnfpsarbestheletnehmeiouisooutnentoeaarnyennbeofgidnrcneepomfteoyeodpgpoalcgaahyscnsanetnanelothroasyuneuitaeiaacueetfpreatflaalmidiadeeetewcurnulhcmiietisaonnsatsgonerirwrmfhushmgeeigultroelsitechttitetsatisawtiaaucnyrcortgilksdflhtediethycreineahwrtmaenohtytensneehmiceedornhnisnawsetotecsgcrtnncstteienesiswtohtulcanecmtsiaaiiehcrucssnogseseatvrlahinoeonhmaidihaefcgtfeeasaewafusucsnaeaowmlonhwemselexehetvnpidaytnmhwoltfnotnrwobnaiftdincutneltkktatneeirtaaaieuwrtleonettrtadadeiicsdnryttniigesatvhurpsdmroiooieihnthtudtoueemelteabiagoeciutnfowmeoodwsoaratofrohteardceyaorbfirbehgalverasahsiulgntiwetrnergehifretssckomtbonulfdiahhsefdhceeyrgitgaaehvetaoenytsieiegetdnthticiomihennbnfeiaitoaneeoihdieaorntlhgoedsfolgaikiihbilieabhlrotstothiwegetoowcagahranhrhieiauviiecealiirdsoehttsoyeliseetermcnlnckurteedhhitdslsontissonhmieesuihwmifuohorhnoydetooerondewguriapoelnotticcgevfiurlncnsaaetwdciruaeundlensiatrenmnehvoeohpmiwstptescmntyeeihlixcwaodehedpseuaeeriuernnaenuettctutdscntfvncemswwodxuotttkotfmesliidemnsditnavtlodhtnmloogwtalbhyiiehrcndiddovtahdanacncsaalouihtokheonsgdtsoswhuptsreoungnwshviteeyuithvalynrthwthtancsdaeigtbnzlibtoswtetrcorotmitecoranditdamkoleantdnaerwruwrsoaysaadewgtenvdtsutyefnttmnalokehhkotaeahegutateyntibetrlabtdtsieupogaeeieplshbpenoeitlcieornflatseietlagmnsnilatetnwsbnwiltiltodistthdcnrttuuiiwrntegtoswlicongnhnyaogsobalaocgnhyratuthooiaegdalrhiraieotetaoeaetjrwsylyuaitealftlwtaahravnrohrsevgecobicaitrdoniaesehaengnteeeraueehoelyteoaoaietilbnioadrigteyaelnnigdalnknadtleteweentethpoyfceerhouoeeeofttuaadmonilistshaagnaalueixuunahetdtvakhiagaontnendheeotpiaerrterstrntrettcneitpukrsyerireedeilhriseontneygldtlfsiadosfohhietieahrfyeiieettfsahtessfslrneacoghbtorseetehinnntuswdheeohrirsndhtklhacrenhhlaniyiras\n"
244 ]
245 }
246 ],
247 "source": [
248 "word_a, score_a = vigenere_frequency_break(sca, fitness=Ptrigrams)\n",
249 "print(word_a, '\\n')\n",
250 "pa = vigenere_decipher(sca, word_a)\n",
251 "print(pa)"
252 ]
253 },
254 {
255 "cell_type": "code",
256 "execution_count": 30,
257 "id": "c7f2e770-8062-4d18-b90a-cb2e410ef88c",
258 "metadata": {},
259 "outputs": [
260 {
261 "name": "stdout",
262 "output_type": "stream",
263 "text": [
264 "jodie i can see why you are concerned but i find it hard to believe that agatha could have been part\n",
265 "of a conspiracy she was a faithful colleague in all the time i worked with her and no one ever\n",
266 "suggested otherwise of course we ran the usual spot checks from time to time but nothing unusual was\n",
267 "found having said that the message you found in the archive is really worrying my first thought was\n",
268 "that she might have been acting as a double agent trying to destabilise nazi intelligence but that\n",
269 "doesnt fit with the text it is crucial to our mission that we maintain the balance of uncertainty\n",
270 "and direct it to our advantage make it look like she had definitely had another agenda i trawled\n",
271 "through my own records to see if anyone else agatha and i worked with might have been involved i\n",
272 "hate to say it but the only person of interest at the moment is charlie we worked together on the\n",
273 "kohinoor twins case and agatha washer great aunt not that treachery is a genetic trait but in\n",
274 "vetting circles it can be treated like it is inherited so i suppose we ought to take that seriously\n",
275 "especially since she became pretty senior in american intelligence i checked our current case files\n",
276 "and although she is retired she still acts as government liaison she is in london at the moment in\n",
277 "the new embassy building which will make it difficult to get hold of her if she wants to stay hidden\n",
278 "we cant afford to upset our us cousins and if we are wrong about her we might also poison the well\n",
279 "when it comes to intelligence exchange they havent for given us for phil by and maclean yet so i can\n",
280 "imagine how they would react if it turns out that one of our own is a double agent and has\n",
281 "infiltrated their inner sanctum i sent one of the elves to take a look at her apartment in new\n",
282 "jersey it was pretty clean as you can imagine but they were able to lift the following extract it\n",
283 "was hard to read and even harder to decipher since she used avi genere encryption but one\n",
284 "incriminating feature stands out even without a decrypt she used the ad morse encoding on top of the\n",
285 "vi genere cipher i am not sure what we should do next could you get the team to take a look at the\n",
286 "file maybe this is all a big coincidence or a misunderstanding if not then we may have to tell\n",
287 "london and washington and i am really not looking forward to that all the best harry\n"
288 ]
289 }
290 ],
291 "source": [
292 "pa = railfence_decipher(sca, key_a)\n",
293 "print(prettify(pa))"
294 ]
295 },
296 {
297 "cell_type": "code",
298 "execution_count": 31,
299 "id": "6cecddd9",
300 "metadata": {
301 "Collapsed": "false"
302 },
303 "outputs": [
304 {
305 "data": {
306 "text/plain": [
307 "2333"
308 ]
309 },
310 "execution_count": 31,
311 "metadata": {},
312 "output_type": "execute_result"
313 }
314 ],
315 "source": [
316 "open(plaintext_a_filename, 'w').write(prettify(pa))"
317 ]
318 },
319 {
320 "cell_type": "code",
321 "execution_count": 32,
322 "id": "77e0eb5c-226d-4197-a687-4a5d725c6af0",
323 "metadata": {},
324 "outputs": [],
325 "source": [
326 "morse_chars = 'a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9'.split()\n",
327 "# morse_chars"
328 ]
329 },
330 {
331 "cell_type": "code",
332 "execution_count": 33,
333 "id": "0c7912fb-f552-4933-9730-3784197fc729",
334 "metadata": {},
335 "outputs": [],
336 "source": [
337 "morse_codes = '.- / -... / -.-. / -.. / . / ..-. / --. / .... / .. / .--- / -.- / .-.. / -- / -. / --- / .--. / --.- / .-. / ... / - / ..- / ...- / .-- / -..- / -.-- / --.. / ----- / .---- / ..--- / ...-- / ....- / ..... / -.... / --... / ---.. / ----.'.split(' / ')"
338 ]
339 },
340 {
341 "cell_type": "code",
342 "execution_count": 34,
343 "id": "ae62967b-0c5d-4e14-adf2-8cad03ed6970",
344 "metadata": {},
345 "outputs": [
346 {
347 "data": {
348 "text/plain": [
349 "['.-', '-...', '-.-.']"
350 ]
351 },
352 "execution_count": 34,
353 "metadata": {},
354 "output_type": "execute_result"
355 }
356 ],
357 "source": [
358 "char_to_morse = {l: c for l, c in zip(morse_chars, morse_codes)}\n",
359 "morse_to_char = {c: l for l, c in zip(morse_chars, morse_codes)}\n",
360 "[char_to_morse[l] for l in 'abc']"
361 ]
362 },
363 {
364 "cell_type": "code",
365 "execution_count": 35,
366 "id": "d5c24bcb-fda8-40f0-89ba-166380046fc9",
367 "metadata": {},
368 "outputs": [
369 {
370 "data": {
371 "text/plain": [
372 "'cdbaneliksgsaztmemhewdmgmydbanadbwyxbuxtynnzelojgrnyhlhyvcyhnrimsynckcifyjyifyjagyhlhuqisnxrunemdcdlhynxolgujdynukugwujynyokhybyannrymscmuftlsmcmuucfgyxkmilsyktbbimgbdbwumeudcbkhfefcvmtcdbanegyfeynngihfyktcquleckgvimkjhocxnwdnrultbonjihsnqtykgdezdzalyccftbovssywyftqryftboskhczjwdientundbwyxsxfonruneuvilozgujncxasnxkndeucnlhyixgnncywmnybsvyvyxtuxslhcxauulbyftzylzalbslozshvizdbwybkxzeqyoddhdbsvyzuksynnzecxpwsnsastcyhlonrysrwruwofyaasncclwiefvhufyyohomlrusaztozmlacbmxolkwliixcsmcxnoogshvsulimtcdcxahiifeyvmwwuccfvycnagudcfgcgimlxcuqwycbgufncynibyatnryqalooflcuydynygskywouhipuzimdijiwkfuulsikinivmtcpufyixyuoovxlrumylhyvcfknyoknignzehrujrskhvjincwalonzeixyktiniatdyxaecculelbcwrqrioohdfwtuxslhcxayoixwwsbobssbolleydbannyclahnbsrlibssvoyfalyofdfyhyehyoyhnyefoqgbwnmygwtbshytlspaafsmscneudlssgholduftixvsluxwwinrcfkcgcdlhoyvtilygnnryyriehvwbolwiwkhzojongihpfmehmylhyncjewdcgnipnzecbyfqoslaempijtboagoxyzwvybsgnygyfeynngkyojsvybsdoqzlgfcvystfouktqrcdenrytomccfvycnagudcgnccbgtmyoflycmlhycsktywzdaacujeuvwjimsmoeqsfdhufyloxsuddighgulkwlipsnaempijaqrcdeqoqalfmujrsyhoinrzgrymuktmlolwcvffonkwlohdbwmoxfwsmdbwtbbystfopwllsmwsnynwnyfyftbohlhymojiugcdlhoyvtiwywtnyxwccnyohydbwrcdckwccylonkewawdcgncgcdlbouvtivifdixngtuuyuhubawozwckdcbyutcyhqoomufcixnscnwystnrywmvkmkywrujlco'"
373 ]
374 },
375 "execution_count": 35,
376 "metadata": {},
377 "output_type": "execute_result"
378 }
379 ],
380 "source": [
381 "morse_table = ''.maketrans('AD', '.-')\n",
382 "cb_dd = cb.translate(morse_table)\n",
383 "cb_words = cb_dd.split(' / ')\n",
384 "cb_letters = cat(cat(morse_to_char[l] for l in w.split()) for w in cb_words)\n",
385 "cb_letters"
386 ]
387 },
388 {
389 "cell_type": "code",
390 "execution_count": 38,
391 "id": "16210c33-3bcb-43c8-9189-d82eea7cf53b",
392 "metadata": {},
393 "outputs": [
394 {
395 "name": "stdout",
396 "output_type": "stream",
397 "text": [
398 "ukusa \n",
399 "\n",
400 "ithinkbossmightsuspectsomethingtheydraftedthereportonthelighthousediscoveryoveramonthagoandhavestillnotforwardedasummarytoushereintheusicantriskmakingenquiriesthroughtheusualchannelsbutithinkweneedtoinvestigateiamdisappointedthatthetrinityteamleftfilesinthebasementwhentheyshippedoutbuttheydidnothavealotofwarningandatleasttheydontseemtohaveleftanythingcurrentforharrytofindiftheyhadhewouldnthavepassedtheinvestigationtothearchaeologistsitwouldhavegonestraightupstairsforactioniamintwomindsaboutitifanyoneelsewasinvestigatingiwouldsayweshouldignoreittheyareunlikelytomakemuchofahistoricalcuriositybutifanyonecouldtracethelinktousnowthenharryandjodiearetheonestodoitjodieisaterrierwhowontletanythinggoonceshehasherteethintoitandharryhasbeenaroundlongenoughtoknowwhensomethingtrivialisactuallyimportantonbalanceithinkiwillneedtobeonthegroundwhereicanhopetoinfluencethedirectionoftheirenquiriesforthegoodofeveryoneweneedtokeepaverylowprofileatleastwhilethebossinvestigationishotsounlessthesystemflagsarealcrisiswewillhavetodialdownouractivitiesforawhilewewillcarryonwithforecastsbutwillnotactonthemunlessthethreatlevelrisestoteneventhenthecuriawillneedtomeettodecidewhetheritiswisetotakeactioniwillheadtolondontotakechargeofmisdirectionyoucancontactmeattheembassycharlie\n"
401 ]
402 }
403 ],
404 "source": [
405 "word_b, score_b = vigenere_frequency_break(cb_letters, fitness=Ptrigrams)\n",
406 "print(word_b, '\\n')\n",
407 "pb = vigenere_decipher(cb_letters, word_b)\n",
408 "print(pb)"
409 ]
410 },
411 {
412 "cell_type": "code",
413 "execution_count": 39,
414 "id": "fe094361-7c85-40d9-952e-0c84abbcf903",
415 "metadata": {},
416 "outputs": [
417 {
418 "name": "stdout",
419 "output_type": "stream",
420 "text": [
421 "i think boss might suspect something they drafted the report on the lighthouse discovery over a\n",
422 "month ago and have still not forwarded a summary to us herein the us icant risk making enquiries\n",
423 "through the usual channels but i think we need to investigate i am disappointed that the trinity\n",
424 "team left files in the basement when they shipped out but they did not have alot of warning and\n",
425 "atleast they dont seem to have left anything current for harry to find if they had he wouldnt have\n",
426 "passed the investigation to the archaeologists it would have gone straight upstairs for action i am\n",
427 "in two minds about it if anyone else was investigating i would say we should ignore it they are\n",
428 "unlikely to make much of a historical curiosity but if anyone could trace the link to us now then\n",
429 "harry and jodie are the ones to do it jodie is a terrier who wont let anything go once she has her\n",
430 "teeth into it and harry has been around long enough to know when something trivial is actually\n",
431 "important on balance i think i will need to be on the ground where i can hope to influence the\n",
432 "direction of their enquiries for the good of everyone we need to keep a very low profile atleast\n",
433 "while the boss investigation is hot so unless the system flags a real crisis we will have to dial\n",
434 "down our activities for a while we will carry on with forecasts but will not acton them unless the\n",
435 "threat level rises to ten even then the curia will need to meet to decide whether it is wise to take\n",
436 "action i will head to london to take charge of misdirection you can contact meat the embassy charlie\n"
437 ]
438 }
439 ],
440 "source": [
441 "pb = vigenere_decipher(cb_letters, word_b)\n",
442 "print(prettify(pb))"
443 ]
444 },
445 {
446 "cell_type": "code",
447 "execution_count": 40,
448 "id": "d12a663c",
449 "metadata": {
450 "Collapsed": "false"
451 },
452 "outputs": [
453 {
454 "data": {
455 "text/plain": [
456 "1563"
457 ]
458 },
459 "execution_count": 40,
460 "metadata": {},
461 "output_type": "execute_result"
462 }
463 ],
464 "source": [
465 "open(plaintext_b_filename, 'w').write(prettify(pb))"
466 ]
467 },
468 {
469 "cell_type": "code",
470 "execution_count": null,
471 "id": "504ec2e2",
472 "metadata": {
473 "Collapsed": "false"
474 },
475 "outputs": [],
476 "source": []
477 }
478 ],
479 "metadata": {
480 "jupytext": {
481 "formats": "ipynb,md"
482 },
483 "kernelspec": {
484 "display_name": "Python 3 (ipykernel)",
485 "language": "python",
486 "name": "python3"
487 },
488 "language_info": {
489 "codemirror_mode": {
490 "name": "ipython",
491 "version": 3
492 },
493 "file_extension": ".py",
494 "mimetype": "text/x-python",
495 "name": "python",
496 "nbconvert_exporter": "python",
497 "pygments_lexer": "ipython3",
498 "version": "3.8.8"
499 }
500 },
501 "nbformat": 4,
502 "nbformat_minor": 5
503 }