Done challenge 2
[cipher-challenge.git] / 2020 / 2020-a-challenge2.ipynb
diff --git a/2020/2020-a-challenge2.ipynb b/2020/2020-a-challenge2.ipynb
new file mode 100644 (file)
index 0000000..be5233b
--- /dev/null
@@ -0,0 +1,218 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 8,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [],
+   "source": [
+    "from szyfrow.affine import *\n",
+    "from szyfrow.keyword_cipher import *"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [],
+   "source": [
+    "challenge_number = 2\n",
+    "plaintext_a_filename = f'plaintext.{challenge_number}a.txt'\n",
+    "plaintext_b_filename = f'plaintext.{challenge_number}b.txt'\n",
+    "ciphertext_a_filename = f'ciphertext.{challenge_number}a.txt'\n",
+    "ciphertext_b_filename = f'ciphertext.{challenge_number}b.txt'"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 9,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [],
+   "source": [
+    "ca = open(ciphertext_a_filename).read()\n",
+    "cb = open(ciphertext_b_filename).read()\n",
+    "scb = sanitise(cb)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 6,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "19 18 True \n",
+      "\n",
+      "The decrypt of the first mission intercept has raised a number of questions about the spyclist operation, if that is what it is, but it has also triggered enquiries about the personnel referenced in that message. Our counterintelligence unit have asked me to task you with enquiries about the names mentioned there, in particular: Jessica; Wilhelm; Nikolaus; Tirpitzufer. It is possible that these are pseudonyms or code names, but they do not appear in our records and CI branch would be very interested in anything you can find out about them in relation to Nazi spy operations. I followed up on the SIS report that Hitler Youth groups travelling abroad were asked to complete a detailed questionnaire, checking if Harry had links that could help with this, and he sent me the attached message that was photographed by a BOSS undercover operative in Berlin. He told me that it had been exfiltrated from Abwehr headquarters and appears to be a request for approval for a new mission, though neither H nor I have had time to break it, so I look forward to receiving your decrypts. We believe the message has been enciphered using a keyword substitution cipher and given that we are not sure how serious the spyclist threat might be we would be grateful if you could decipher it quickly. The message was also a reminder to me that our own security is an important consideration, so I will also switch to a keyword substitution cipher for the next Mission Briefing. Pearl.\n",
+      "\n"
+     ]
+    }
+   ],
+   "source": [
+    "(m_a, a_a, o_a), score_a = affine_break(ca)\n",
+    "print(m_a, a_a, o_a, '\\n')\n",
+    "pa = affine_decipher(ca, m_a, a_a, o_a)\n",
+    "print(pa)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 7,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "1471"
+      ]
+     },
+     "execution_count": 7,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "open(plaintext_a_filename, 'w').write(pa)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 17,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "archerys KeywordWrapAlphabet.from_last \n",
+      "\n",
+      "attdctioc w our missioc to dmnde sympathisdrs ic thd ul dstanfishmdct is goicg wdff afthough thd rdkdct ickrdasd ic eipfomatik tdcsioc has sigcibikactfy ickrdasde thd risl bor our agdcts ic kommucikaticg with thdir hacefdrs. with tdfdgram trabbik ucedr dchackde supdrvisioc ny thd ul ictdffigdckd orgacisatiocs it is afso ickrdasicgfy eibbikuft bor thd agdcts ace thdir hacefdrs to rdpatriatd ictdffigdckd rdports ob acy sigcibikackd. thd usd ob naclicg kiphdrs is co focgdr rdgarede as sdkurd ace edspitd its onvious aevactagds, thd dcigma is too vafuanfd to us to affow its usd ndhice dcdmy ficds. bor cow, wd ard dckouragicg our agdcts to usd a mix ob ldywore ace tracspositioc kiphdrs as taught ic thdir nasik traicicg, sickd thdsd ard rdfianfd ace eo cot rdquird thd agdcts to nd ic possdssioc ob mord thac a sdrids ob ldy wores ace phrasds, whikh thdy ard wdff anfd to mdmorisd. as thd quactity ob sigcafs trabbik ickrdasds wd wiff cdde to rdkocsiedr our protokofs, nut bor cow i thicl our bokus shoufe nd oc edvdfopicg sdkurd kommucikatioc khaccdfs, with kut-outs to isofatd our mord vafuanfd assdts. i eiskussde this issud with my kouctdrpart ic edpartmdct ih who is a lddc kykfist ace hd maed a rathdr icgdcious suggdstioc that wd might mald gooe usd ob thd hitfdr youth. a cumndr ob partids havd nddc icvitde to visit thd ul oc kykficg tours ace hd hae nddc kocsiedricg aslicg thdm to rdkore icbormatioc anout thd fayout ob mifitary ace iceustriaf facemarls as part ob his ictdffigdckd gathdricg opdratioc. it is highfy fildfy that acy war wiff icvofvd a protraktde nomnicg kampaigc ace up to eatd maps wiff nd ob grdat vafud ic our pfaccicg. burthdrmord, thd kouctrysied roae fayouts ic thd ul ard cotorious bor thdir icdbbikidcky ace acy icvasioc, woufe nd sdvdrdfy hampdrde ny our fakl ob lcowfdegd ob tracsport cdtworls. hd hae erabtde ac appardctfy rathdr iccokuous artikfd bor thd cazi kykfist assokiatioc magazicd with a fist ob thicgs that our youcg kykfists might bice ictdrdsticg: imprdss oc your mdmory thd roaes ace paths, viffagds ace towcs, outstaceicg khurkh towdrs ace othdr facemarls so that you wiff cot borgdt thdm. mald a cotd ob thd camds, pfakds, rivdrs, sdas ace mouctaics. pdrhaps you may nd anfd to utifisd thdsd somd timd bor thd ndcdbit ob thd bathdrface. shoufe you komd to a nriegd whikh ictdrdsts you, dxamicd its kocstruktioc ace thd matdriafs usde. fdarc to mdasurd ace dstimatd thd wieth ob strdams. waed through bores so that you wiff nd anfd to bice thdm ic thd earl. i proposd that wd kocsiedr usicg thdsd assdts as thd kut-outs ndtwddc our ucedrkovdr agdcts ace thdir hacefdrs ic thd ul ace our kommucikatiocs cdtworl. thdy ard rdfativdfy brdd to movd arouce thd kouctry ace kac dasify nd traicde to usd erop-obbs ace othdr spykrabt to affow thdm to koffdkt ictdffigdckd rdports ace pass thdm oc. thd marvdffous postd rdstactd systdm affows us to kommucikatd with thdm, ace a suitanfd koednool woufe affow us to tracsmit icstruktiocs ic pfaic tdxt with co risl that thd mdacicg koufe nd eiskdrcde ny kouctdrictdffigdckd opdrativds ic thd postaf sdrvikd. i havd acothdr thought anout how wd might dxpfoit this cdtworl burthdr, howdvdr i cdde to worl through somd mord edtaifs ndbord i eiskuss it with you, ace i wactde to khdkl that you ard happy bor md to affokatd rdsourkds to traic a cumndr ob hitfdr youth ic thd rdquirde sliffs bor this opdratioc. cr.\n",
+      "\n"
+     ]
+    }
+   ],
+   "source": [
+    "(word_b, wrap_b), score_b = keyword_break_mp(scb, fitness=Ptrigrams)\n",
+    "print(word_b, wrap_b, '\\n')\n",
+    "pb = keyword_decipher(cb, word_b, wrap_b)\n",
+    "print(pb)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 20,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "abwehrstuvxyzcdfgijklmnopq \n",
+      "\n",
+      "attention w our mission to embed sympathisers in the uk establishment is going well although the recent increase in diplomatic tension has significantly increased the risk for our agents in communicating with their handlers. with telegram traffic under enhanced supervision by the uk intelligence organisations it is also increasingly difficult for the agents and their handlers to repatriate intelligence reports of any significance. the use of banking ciphers is no longer regarded as secure and despite its obvious advantages, the enigma is too valuable to us to allow its use behind enemy lines. for now, we are encouraging our agents to use a mix of keyword and transposition ciphers as taught in their basic training, since these are reliable and do not require the agents to be in possession of more than a series of key words and phrases, which they are well able to memorise. as the quantity of signals traffic increases we will need to reconsider our protocols, but for now i think our focus should be on developing secure communication channels, with cut-outs to isolate our more valuable assets. i discussed this issue with my counterpart in department ih who is a keen cyclist and he made a rather ingenious suggestion that we might make good use of the hitler youth. a number of parties have been invited to visit the uk on cycling tours and he had been considering asking them to record information about the layout of military and industrial landmarks as part of his intelligence gathering operation. it is highly likely that any war will involve a protracted bombing campaign and up to date maps will be of great value in our planning. furthermore, the countryside road layouts in the uk are notorious for their inefficiency and any invasion, would be severely hampered by our lack of knowledge of transport networks. he had drafted an apparently rather innocuous article for the nazi cyclist association magazine with a list of things that our young cyclists might find interesting: impress on your memory the roads and paths, villages and towns, outstanding church towers and other landmarks so that you will not forget them. make a note of the names, places, rivers, seas and mountains. perhaps you may be able to utilise these some time for the benefit of the fatherland. should you come to a bridge which interests you, examine its construction and the materials used. learn to measure and estimate the width of streams. wade through fords so that you will be able to find them in the dark. i propose that we consider using these assets as the cut-outs between our undercover agents and their handlers in the uk and our communications network. they are relatively free to move around the country and can easily be trained to use drop-offs and other spycraft to allow them to collect intelligence reports and pass them on. the marvellous poste restante system allows us to communicate with them, and a suitable codebook would allow us to transmit instructions in plain text with no risk that the meaning could be discerned by counterintelligence operatives in the postal service. i have another thought about how we might exploit this network further, however i need to work through some more details before i discuss it with you, and i wanted to check that you are happy for me to allocate resources to train a number of hitler youth in the required skills for this operation. nr.\n",
+      "\n"
+     ]
+    }
+   ],
+   "source": [
+    "word_b, score_b = simulated_annealing_break(scb)\n",
+    "print(word_b, '\\n')\n",
+    "pb = keyword_decipher(cb, word_b)\n",
+    "print(pb)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 19,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "'attention w our mission to embed sympathisers in the uk establishment is going well although the recent increase in diplomatic tension has significantly increased the risk for our agents in communicating with their handlers. with telegram traffic under enhanced supervision by the uk intelligence organisations it is also increasingly difficult for the agents and their handlers to repatriate intelligence reports of any significance. the use of banking ciphers is no longer regarded as secure and despite its obvious advantages, the enigma is too valuable to us to allow its use behind enemy lines. for now, we are encouraging our agents to use a mix of keyword and transposition ciphers as taught in their basic training, since these are reliable and do not require the agents to be in possession of more than a series of key words and phrases, which they are well able to memorise. as the quantity of signals traffic increases we will need to reconsider our protocols, but for now i think our focus should be on developing secure communication channels, with cut-outs to isolate our more valuable assets. i discussed this issue with my counterpart in department ih who is a keen cyclist and he made a rather ingenious suggestion that we might make good use of the hitler youth. a number of parties have been invited to visit the uk on cycling tours and he had been considering asking them to record information about the layout of military and industrial landmarks as part of his intelligence gathering operation. it is highly likely that any war will involve a protracted bombing campaign and up to date maps will be of great value in our planning. furthermore, the countryside road layouts in the uk are notorious for their inefficiency and any invasion, would be severely hampered by our lack of knowledge of transport networks. he had drafted an apparently rather innocuous article for the nazi cyclist association magazine with a list of things that our young cyclists might find interesting: impress on your memory the roads and paths, villages and towns, outstanding church towers and other landmarks so that you will not forget them. make a note of the names, places, rivers, seas and mountains. perhaps you may be able to utilise these some time for the benefit of the fatherland. should you come to a bridge which interests you, examine its construction and the materials used. learn to measure and estimate the width of streams. wade through fords so that you will be able to find them in the dark. i propose that we consider using these assets as the cut-outs between our undercover agents and their handlers in the uk and our communications network. they are relatively free to move around the country and can easily be trained to use drop-offs and other spycraft to allow them to collect intelligence reports and pass them on. the marvellous poste restante system allows us to communicate with them, and a suitable codebook would allow us to transmit instructions in plain text with no risk that the meaning could be discerned by counterintelligence operatives in the postal service. i have another thought about how we might exploit this network further, however i need to work through some more details before i discuss it with you, and i wanted to check that you are happy for me to allocate resources to train a number of hitler youth in the required skills for this operation. nr.\\n'"
+      ]
+     },
+     "execution_count": 19,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "keyword_decipher(cb, 'abwehr', KeywordWrapAlphabet.from_last)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 21,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "3403"
+      ]
+     },
+     "execution_count": 21,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "open(plaintext_b_filename, 'w').write(pb)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {
+    "Collapsed": "false"
+   },
+   "outputs": [],
+   "source": []
+  }
+ ],
+ "metadata": {
+  "jupytext": {
+   "formats": "ipynb,md"
+  },
+  "kernelspec": {
+   "display_name": "Python 3",
+   "language": "python",
+   "name": "python3"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3",
+   "version": "3.7.4"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}