Done challenge 9
[cipher-challenge.git] / 2021 / 2021-challenge9.md
1 ---
2 jupyter:
3 jupytext:
4 formats: ipynb,md
5 text_representation:
6 extension: .md
7 format_name: markdown
8 format_version: '1.3'
9 jupytext_version: 1.11.1
10 kernelspec:
11 display_name: Python 3 (ipykernel)
12 language: python
13 name: python3
14 ---
15
16 ```python Collapsed="false"
17 from szyfrow.caesar import *
18 from szyfrow.affine import *
19 from szyfrow.keyword_cipher import *
20 from szyfrow.column_transposition import *
21 from szyfrow.vigenere import *
22 from szyfrow.polybius import *
23 from szyfrow.railfence import *
24 from szyfrow.hill import *
25 from szyfrow.support.text_prettify import *
26
27 import numpy as np
28 import pandas as pd
29 import matplotlib.pyplot as plt
30
31 import collections
32 %matplotlib inline
33 ```
34
35 ```python Collapsed="false"
36 challenge_number = 9
37 plaintext_a_filename = f'plaintext.{challenge_number}a.txt'
38 plaintext_b_filename = f'plaintext.{challenge_number}b.txt'
39 ciphertext_a_filename = f'ciphertext.{challenge_number}a.txt'
40 ciphertext_b_filename = f'ciphertext.{challenge_number}b.txt'
41 ```
42
43 ```python Collapsed="false"
44 ca = open(ciphertext_a_filename).read()
45 cb = open(ciphertext_b_filename).read()
46
47
48 sca = sanitise(ca)
49 rsca = cat(reversed(sca))
50 scb = sanitise(cb)
51 rscb = cat(reversed(scb))
52 ```
53
54 ```python
55 sca_counts = collections.Counter(sca)
56 sca_counts
57 ```
58
59 ```python tags=[]
60 pd.Series(sca_counts).sort_index().plot.bar()
61 ```
62
63 ```python
64 import itertools
65 ```
66
67 ```python
68 permutes = [transpositions_of(cat(t)) for t in itertools.permutations('abcdefghi')]
69 len(permutes)
70 ```
71
72 ```python
73 key_a, _ = column_transposition_break(sca, translist=permutes, fitness=Ptrigrams)
74 word_a, fill_a, empty_a = key_a
75 word_a, fill_a, empty_a
76 ```
77
78 ```python
79 # mod_word_a = (1, 3, 6, 4, 5, 7, 0, 2, 8)
80 pa = column_transposition_decipher(sca, word_a,
81 fillcolumnwise=fill_a, emptycolumnwise=empty_a)
82 pa
83 ```
84
85 ```python
86 print(prettify(pa))
87 ```
88
89 ```python Collapsed="false" tags=[]
90 open(plaintext_a_filename, 'w').write(prettify(pa))
91 ```
92
93 ```python
94 scb_counts = collections.Counter(scb)
95 scb_counts
96 ```
97
98 ```python tags=[]
99 pd.Series(scb_counts).sort_index().plot.bar()
100 ```
101
102 ```python
103 key_b, _ = hill_break(scb, fitness=Ptrigrams)
104 ```
105
106 ```python
107 key_b
108 ```
109
110 ```python
111 pb = hill_decipher(key_b, scb)
112 pb
113 ```
114
115 ```python
116 print(prettify(pb))
117 ```
118
119 ```python Collapsed="false"
120 open(plaintext_b_filename, 'w').write(prettify(pb))
121 ```
122
123 ```python Collapsed="false"
124
125 ```