8590e9b46aa9991cbebdd3d4deffeb97c51ecd75
[szyfrow.git] / pocket_enigma.py
1 from szyfrow.support.utilities import *
2 from szyfrow.support.language_models import *
3
4
5 class PocketEnigma(object):
6 """A pocket enigma machine
7 The wheel is internally represented as a 26-element list self.wheel_map,
8 where wheel_map[i] == j shows that the position i places on from the arrow
9 maps to the position j places on.
10 """
11 def __init__(self, wheel=1, position='a'):
12 """initialise the pocket enigma, including which wheel to use and the
13 starting position of the wheel.
14
15 The wheel is either 1 or 2 (the predefined wheels) or a list of letter
16 pairs.
17
18 The position is the letter pointed to by the arrow on the wheel.
19
20 >>> pe.wheel_map
21 [25, 4, 23, 10, 1, 7, 9, 5, 12, 6, 3, 17, 8, 14, 13, 21, 19, 11, 20, 16, 18, 15, 24, 2, 22, 0]
22 >>> pe.position
23 0
24 """
25 self.wheel1 = [('a', 'z'), ('b', 'e'), ('c', 'x'), ('d', 'k'),
26 ('f', 'h'), ('g', 'j'), ('i', 'm'), ('l', 'r'), ('n', 'o'),
27 ('p', 'v'), ('q', 't'), ('s', 'u'), ('w', 'y')]
28 self.wheel2 = [('a', 'c'), ('b', 'd'), ('e', 'w'), ('f', 'i'),
29 ('g', 'p'), ('h', 'm'), ('j', 'k'), ('l', 'n'), ('o', 'q'),
30 ('r', 'z'), ('s', 'u'), ('t', 'v'), ('x', 'y')]
31 if wheel == 1:
32 self.make_wheel_map(self.wheel1)
33 elif wheel == 2:
34 self.make_wheel_map(self.wheel2)
35 else:
36 self.validate_wheel_spec(wheel)
37 self.make_wheel_map(wheel)
38 if position in string.ascii_lowercase:
39 self.position = pos(position)
40 else:
41 self.position = position
42
43 def make_wheel_map(self, wheel_spec):
44 """Expands a wheel specification from a list of letter-letter pairs
45 into a full wheel_map.
46
47 >>> pe.make_wheel_map(pe.wheel2)
48 [2, 3, 0, 1, 22, 8, 15, 12, 5, 10, 9, 13, 7, 11, 16, 6, 14, 25, 20, 21, 18, 19, 4, 24, 23, 17]
49 """
50 self.validate_wheel_spec(wheel_spec)
51 self.wheel_map = [0] * 26
52 for p in wheel_spec:
53 self.wheel_map[pos(p[0])] = pos(p[1])
54 self.wheel_map[pos(p[1])] = pos(p[0])
55 return self.wheel_map
56
57 def validate_wheel_spec(self, wheel_spec):
58 """Validates that a wheel specificaiton will turn into a valid wheel
59 map.
60
61 >>> pe.validate_wheel_spec([])
62 Traceback (most recent call last):
63 ...
64 ValueError: Wheel specification has 0 pairs, requires 13
65 >>> pe.validate_wheel_spec([('a', 'b', 'c')]*13)
66 Traceback (most recent call last):
67 ...
68 ValueError: Not all mappings in wheel specificationhave two elements
69 >>> pe.validate_wheel_spec([('a', 'b')]*13)
70 Traceback (most recent call last):
71 ...
72 ValueError: Wheel specification does not contain 26 letters
73 """
74 if len(wheel_spec) != 13:
75 raise ValueError("Wheel specification has {} pairs, requires 13".
76 format(len(wheel_spec)))
77 for p in wheel_spec:
78 if len(p) != 2:
79 raise ValueError("Not all mappings in wheel specification"
80 "have two elements")
81 if len(set([p[0] for p in wheel_spec] +
82 [p[1] for p in wheel_spec])) != 26:
83 raise ValueError("Wheel specification does not contain 26 letters")
84
85 def encipher_letter(self, letter):
86 """Enciphers a single letter, by advancing the wheel before looking up
87 the letter on the wheel.
88
89 >>> pe.set_position('f')
90 5
91 >>> pe.encipher_letter('k')
92 'h'
93 """
94 self.advance()
95 return self.lookup(letter)
96 decipher_letter = encipher_letter
97
98 def lookup(self, letter):
99 """Look up what a letter enciphers to, without turning the wheel.
100
101 >>> pe.set_position('f')
102 5
103 >>> cat([pe.lookup(l) for l in string.ascii_lowercase])
104 'udhbfejcpgmokrliwntsayqzvx'
105 >>> pe.lookup('A')
106 ''
107 """
108 if letter in string.ascii_lowercase:
109 return unpos(
110 (self.wheel_map[(pos(letter) - self.position) % 26] +
111 self.position))
112 else:
113 return ''
114
115 def advance(self):
116 """Advances the wheel one position.
117
118 >>> pe.set_position('f')
119 5
120 >>> pe.advance()
121 6
122 """
123 self.position = (self.position + 1) % 26
124 return self.position
125
126 def encipher(self, message, starting_position=None):
127 """Enciphers a whole message.
128
129 >>> pe.set_position('f')
130 5
131 >>> pe.encipher('helloworld')
132 'kjsglcjoqc'
133 >>> pe.set_position('f')
134 5
135 >>> pe.encipher('kjsglcjoqc')
136 'helloworld'
137 >>> pe.encipher('helloworld', starting_position = 'x')
138 'egrekthnnf'
139 """
140 if starting_position:
141 self.set_position(starting_position)
142 transformed = ''
143 for l in message:
144 transformed += self.encipher_letter(l)
145 return transformed
146 decipher = encipher
147
148 def set_position(self, position):
149 """Sets the position of the wheel, by specifying the letter the arrow
150 points to.
151
152 >>> pe.set_position('a')
153 0
154 >>> pe.set_position('m')
155 12
156 >>> pe.set_position('z')
157 25
158 """
159 self.position = pos(position)
160 return self.position
161
162
163 def pocket_enigma_break_by_crib(message, wheel_spec, crib, crib_position):
164 """Break a pocket enigma using a crib (some plaintext that's expected to
165 be in a certain position). Returns a list of possible starting wheel
166 positions that could produce the crib.
167
168 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'h', 0)
169 ['a', 'f', 'q']
170 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'he', 0)
171 ['a']
172 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'll', 2)
173 ['a']
174 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'l', 2)
175 ['a']
176 >>> pocket_enigma_break_by_crib('kzpjlzmoga', 1, 'l', 3)
177 ['a', 'j', 'n']
178 >>> pocket_enigma_break_by_crib('aaaaa', 1, 'l', 3)
179 []
180 """
181 pe = PocketEnigma(wheel=wheel_spec)
182 possible_positions = []
183 for p in string.ascii_lowercase:
184 pe.set_position(p)
185 plaintext = pe.decipher(message)
186 if plaintext[crib_position:crib_position+len(crib)] == crib:
187 possible_positions += [p]
188 return possible_positions
189
190 if __name__ == "__main__":
191 import doctest
192 doctest.testmod(extraglobs={'pe': PocketEnigma(1, 'a')})