secretcodes.html


001| '''Secret Codes: Classes for (simply) encoded text messages.
001| 
001| Classes:
001|     SecretCodeMachine   (name)      - Abstract base class for encoding classes
001|     DecoderRing         (setting)   - Basic rotating substitution code
001|     Triplet13Code       (triplet)   - Substitution code from Robert J. Sawyer's Triggers
001|     PlayfairCode        (keyword)   - Playfair cipher
001|     TypewriterCode      (keyboard)  - Typewriter code (a la Sue Grafton's X)
001| 
001| '''

002| ####################################################################################################
003| from random import randint
004| ####################################################################################################
005| 
006| 
007| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
008| class SecretCodeMachine ():
009|     '''Abstract base class for Secret Code classes.'''
010| 
011|     def __init__ (self, name='Enigma'):
012|         self.name = name
013| 
014|     def __str__ (self):
015|         return self.name
016| 
017|     def encode (self, plaintext):
018|         '''<base class must override!>'''
019|         return plaintext
020| 
021|     def decode (self, ciphertext):
022|         '''<base class must override!>'''
023|         return ciphertext
024| 
025|     def chunker (self, chs, chunk_min=2, chunk_max=7):
026|         '''Strip spaces and break text into chunks.'''
027|         txt = [ch for ch in chs if ch.isalpha()]
028|         buf = []
029|         while len(txt):
030|             dx = randint(chunk_min, chunk_max)
031|             buf.append(''.join(txt[0:dx]))
032|             del txt[0:dx]
033|         return ' '.join(buf)
034| 
035| 
036| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
037| class DecoderRing (SecretCodeMachine):
038|     '''Basic decoder ring encryption.'''
039|     alphas = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
040| 
041|     def __init__ (self, setting):
042|         super().__init__('DecoderRing')
043|         assert (0 <= setting <= 25), RuntimeError('Invalid setting: %s' % str(setting))
044|         self.setting = setting
045|         self.ring = (self.alphas+self.alphas)[self.setting:self.setting+26]
046| 
047|     def encode (self, clrtxt, spaces=True, chunk=False, chunk_min=5, chunk_max=5):
048|         '''Return an encoded string.'''
049|         if spaces:
050|             chs = [ch.upper() for ch in clrtxt if ch.isalpha() or ch.isspace()]
051|         else:
052|             chs = [ch.upper() for ch in clrtxt if ch.isalpha()]
053|         buf = []
054|         for ch in chs:
055|             if ch.isspace():
056|                 buf.append(ch)
057|                 continue
058|             cx = self.alphas.index(ch)
059|             buf.append(self.ring[cx])
060|         enctxt = ''.join(buf)
061|         if chunk:
062|             return self.chunker(enctxt, chunk_min, chunk_max)
063|         return enctxt
064| 
065|     def decode (self, enctxt, spaces=True, chunk=False, chunk_min=12, chunk_max=12):
066|         '''Return a decoded string.'''
067|         if spaces:
068|             chs = [ch.upper() for ch in enctxt if ch.isalpha() or ch.isspace()]
069|         else:
070|             chs = [ch.upper() for ch in enctxt if ch.isalpha()]
071|         buf = []
072|         for ch in chs:
073|             if ch.isspace():
074|                 buf.append(ch)
075|                 continue
076|             cx = self.ring.index(ch)
077|             buf.append(self.alphas[cx])
078|         clrtxt = ''.join(buf)
079|         if chunk:
080|             return self.chunker(clrtxt, chunk_min, chunk_max)
081|         return clrtxt
082| 
083|     def __str__ (self):
084|         return self.ring
085| 
086|     def __repr__ (self):
087|         t = (self.setting, self.ring)
088|         s = '{DecoderRing:{setting:%d, ring:"%s"}}'
089|         return s%t
090| 
091| 
092| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
093| class Triplet13Code (SecretCodeMachine):
094|     '''Substitution code from Robert J. Sawyer's Triggers.'''
095| 
096|     def __init__ (self, triplet=(0,0,13)):
097|         '''New instance of a Triplet code machine.'''
098|         super().__init__('Triplet13')
099|         assert len(triplet)==3, RuntimeError('Invalid input: %s' % str(triplet))
100|         assert sum(triplet)==13, RuntimeError('Invalid code triple: %s' % str(triplet))
101|         self.triplet = triplet
102|         self.table= {' ':' '}
103|         # Build the encryption table...
104|         self._make_table()
105| 
106|     def __str__ (self):
107|         return 'Triplet: %d %d %d' % self.triplet
108| 
109|     def parse (self, enctxt, **kwargs):
110|         '''Decode ciphertext with a Triplet prefix.'''
111|         parts = enctxt.split(maxsplit=3)
112|         triplet = (int(parts[0]), int(parts[1]), int(parts[2]))
113|         assert len(parts)==4, RuntimeError('Invalid input: %s' % enctxt)
114|         assert sum(triplet)==13, RuntimeError('Invalid code triple: %s' % str(triplet))
115|         self.triplet = triplet
116|         self.table= {' ':' '}
117|         # Build the encryption table...
118|         self._make_table()
119|         return self.decode(parts[3], **kwargs)
120| 
121|     def encode (self, clrtxt, **kwargs):
122|         '''Encode plaintext. Emits ciphertext with a Triplet prefix (use decode to make only ciphertext).'''
123|         enc = self._xxcode(clrtxt, **kwargs)
124|         enctxt = '%d %d %d %s' % (*self.triplet, enc)
125|         return enctxt
126| 
127|     def decode (self, txt, **kwargs):
128|         '''Decode ciphertext. Also: Encode plaintext without emitting a prefix.'''
129|         return self._xxcode(txt, **kwargs)
130| 
131|     def _xxcode (self, txt_in, spaces=True, chunk=False, chunk_min=5, chunk_max=5):
132|         '''Coding is symmetrical, so encode and decode use the same function.'''
133|         if spaces:
134|             chs = [ch.upper() for ch in txt_in if ch.isalpha() or ch.isspace()]
135|         else:
136|             chs = [ch.upper() for ch in txt_in if ch.isalpha()]
137|         buf = []
138|         for ch in chs:
139|             buf.append(self.table[ch])
140|         txt_out = ''.join(buf)
141|         return (self.chunker(txt_out, chunk_min,chunk_max) if chunk else txt_out)
142| 
143|     def _make_table (self):
144|         '''Given the current Triplet, generate the code table.'''
145|         alphas = [chr(ord('A')+n) for n in reversed(range(26))]
146|         # For each part of the Triplet code...
147|         for n in self.triplet:
148|             stack = []
149|             # Grab that many alphas...
150|             for ix in range(n):
151|                 stack.append(alphas.pop())
152|             # And pair them with that many more...
153|             for ch1 in stack:
154|                 ch2 = alphas.pop()
155|                 self.table[ch1] = ch2 # A -> x
156|                 self.table[ch2] = ch1 # x -> A
157| 
158| 
159| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
160| class PlayfairCode (SecretCodeMachine):
161|     '''Playfair Cipher class.
161| 
161| Usage:
161|     obj = Playfair(keyword)
161|     code = obj.encode(text)
161|     text = obj.decode(code)
161| 
161| Methods:
161|     encode(text)    - Encode text
161|     decode(code)    - Decode code
161|     str(obj)        - return string of code grid
161| 
161| Properties:
161|     .grid   - 5x5 code grid
161|     .msg    - input string after conditioning
161|     .txt    - output string
161|     .enc    - (private)
161|     ._ps    - (private)
161|     ._gs    - (private)
161| 
161| '''

162|     A2Z = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
163| 
164|     def __init__ (self, keyword):
165|         '''New Playfair cipher object. Takes a keyword.'''
166|         super().__init__('PlayfairCode')
167|         rs = range(5)
168|         kw = []
169|         for ch in keyword.upper():
170|             if (ch in self.A2Z) and (ch not in kw):
171|                 kw.append(ch)
172|         az = [a for a in self.A2Z if a not in kw]
173|         cs = list(reversed(kw+az))
174|         self.grid = [[[cs.pop(),r,c] for c in rs] for r in rs]
175|         self.msg = ''
176|         self.txt = ''
177|         self.enc = None
178|         self._ps = None
179|         self._gs = None
180| 
181|     def encode (self, plaintext):
182|         '''Encode plain text.'''
183|         self.msg = self._condition_message(plaintext)
184|         self._ps = [self._find_pair(m) for m in self.msg]
185|         self._gs = [self._encode_pair(p0,p1) for p0,p1 in self._ps]
186|         self.enc = [(g[0][0], g[1][0]) for g in self._gs]
187|         self.txt = ''.join([a[0]+a[1] for a in self.enc])
188|         return self.txt
189| 
190|     def decode (self, ciphertext):
191|         '''Decode cipher text.'''
192|         self.msg = self._condition_message(ciphertext)
193|         self._ps = [self._find_pair(m) for m in self.msg]
194|         self._gs = [self._decode_pair(p0,p1) for p0,p1 in self._ps]
195|         self.enc = [(g[0][0], g[1][0]) for g in self._gs]
196|         self.txt = ''.join([a[0]+a[1] for a in self.enc])
197|         self.txt = self.txt.rstrip('Q')
198|         ix = self.txt.find('Q')
199|         while 0 < ix:
200|             if self.txt[ix-1] == self.txt[ix+1]:
201|                 self.txt = self.txt[0:ix]+self.txt[ix+1:]
202|             ix = self.txt.find('Q', ix+1)
203|         return self.txt
204| 
205|     def __str__ (self):
206|         '''Return a string version of the code grid.'''
207|         a = [str(row) for row in self.grid]
208|         return '\n'.join(a)
209| 
210|     def _find_pair (self, pair):
211|         '''Find a pair of letters in the code grid.'''
212|         c0,c1 = pair
213|         rc0,rc1 = (0,0), (0,0)
214|         for row in self.grid:
215|             for col in row:
216|                 if col[0] == c0:
217|                     rc0 = (col[1],col[2])
218|                 if col[0] == c1:
219|                     rc1 = (col[1],col[2])
220|         return rc0,rc1
221| 
222|     def _encode_pair (self, rc0, rc1):
223|         '''Encode a pair of characters in the grid.'''
224|         if (rc0[0]==rc1[0]) and (rc0[1]==rc1[1]):
225|             # Same row and column...
226|             raise RuntimeError('Attempt to encode matching pair: "%s"' % rc0)
227|         if rc0[0] == rc1[0]:
228|             # Same row...
229|             c0 = self.grid[rc0[0]][(rc0[1]+1)%5]
230|             c1 = self.grid[rc1[0]][(rc1[1]+1)%5]
231|             return c0,c1
232|         if rc0[1] == rc1[1]:
233|             # Same column...
234|             c0 = self.grid[(rc0[0]+1)%5][rc0[1]]
235|             c1 = self.grid[(rc1[0]+1)%5][rc1[1]]
236|             return c0,c1
237|         # Different row and column...
238|         c0 = self.grid[rc0[0]][rc1[1]]
239|         c1 = self.grid[rc1[0]][rc0[1]]
240|         return c0,c1
241| 
242|     def _decode_pair (self, rc0, rc1):
243|         '''Decode a pair of characters in the grid.'''
244|         if (rc0[0]==rc1[0]) and (rc0[1]==rc1[1]):
245|             # Same row and column...
246|             raise RuntimeError('Attempt to decode matching pair: "%s"' % rc0)
247|         if rc0[0] == rc1[0]:
248|             # Same row...
249|             c0 = self.grid[rc0[0]][(rc0[1]-1)%5]
250|             c1 = self.grid[rc1[0]][(rc1[1]-1)%5]
251|             return c0,c1
252|         if rc0[1] == rc1[1]:
253|             # Same column...
254|             c0 = self.grid[(rc0[0]-1)%5][rc0[1]]
255|             c1 = self.grid[(rc1[0]-1)%5][rc1[1]]
256|             return c0,c1
257|         # Different row and column...
258|         c0 = self.grid[rc0[0]][rc1[1]]
259|         c1 = self.grid[rc1[0]][rc0[1]]
260|         return c0,c1
261| 
262|     def _condition_message (self, message):
263|         '''Condition a message for Playfair input:
263|     + Force to uppercase;
263|     + convert J to I;
263|     + split double letter pairs with Q;
263|     + end with 'Q' if necessary to fill out last pair.
263| '''

264|         mesg = []
265|         state = 0
266|         tempc = ''
267|         for ch in message.upper():
268|             if ch.isalpha():
269|                 # Convert any 'J' to an 'I'...
270|                 if ch == 'J':
271|                     ch = 'I'
272|                 if state:
273|                     if ch == tempc:
274|                         t = (tempc, 'Q')
275|                         mesg.append(t)
276|                         continue
277|                     t = (tempc, ch)
278|                     mesg.append(t)
279|                     state = 0
280|                 else:
281|                     tempc = ch
282|                     state = 1
283|         if state:
284|             t = (tempc, 'Q')
285|             mesg.append(t)
286|         return mesg
287| 
288| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
289| class TypewriterCode (SecretCodeMachine):
290|     '''Typewriter code from Sue Grafton's Penultimate Kinsey Millhone novel, 'X'.'''
291|     keyboards =[   [   ' ',
292|             'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
293|             'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
294|             'z', 'x', 'c', 'v', 'b', 'n', 'm',
295|             '\r', '\n'
296|         ]
297|     ,   [   ' ','!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+',
298|             '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
299|             'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ':', '"', '\r','\n'
300|             'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.','?',
301|         ]
302|     ]
303| 
304|     def __init__ (self, keyboard=0):
305|         super().__init__('TypewriterCode')
306|         self.mode = keyboard
307|         self.kybd = TypewriterCode.keyboards[keyboard]
308|         self.ltrs = dict([(c,cx) for cx,c in enumerate(self.kybd)])
309| 
310|     def __str__ (self):
311|         return self.kybd
312| 
313|     def encode (self, plaintext):
314|         buf = []
315|         for ch in plaintext.lower():
316|             if ch in self.ltrs:
317|                 buf.append(self.ltrs[ch])
318|         return buf
319| 
320|     def decode (self, ciphertext):
321|         buf = []
322|         for c in ciphertext:
323|             buf.append(self.kybd[c])
324|         txt = ''.join(buf)
325|         return txt
326| 
327|     def prettyprint (self, codes, columns=10):
328|         # We need an even number of codes...
329|         if len(codes) % 2:
330|             codes.append(0)
331|         # Generate pairs of codes...
332|         self.ts = [n*2 for n in range(len(codes)//2)]
333|         self.ps = [tuple(codes[ix:ix+2]) for ix in self.ts]
334|         # Generate strings of the paired codes...
335|         self.ss = ['%02d%02d' % p for p in self.ps]
336|         # Create output string...
337|         out = []
338|         buf = []
339|         for ix,s in enumerate(self.ss):
340|             if (0 < ix) and ((ix % columns) == 0):
341|                 out.append(' '.join(buf))
342|                 buf = []
343|             buf.append(s)
344|         if 0 < len(buf):
345|             out.append(' '.join(buf))
346|         return '\n'.join(out)
347| 
348| 
349| ####################################################################################################
350| '''eof'''
351|