enigma.html


001| '''Enigma Machine Software Model.
001| 
001| Resources:
001|     https://en.wikipedia.org/wiki/Enigma_machine
001| 
001| Classes:
001|     EnigmaWheel         (gid, wid)
001|     EnigmaPlugBoard     (plugs)
001|     EnigmaReflector     (cs, mode=0)
001|     EnigmaMachine       (gid, wids, loadlib=False)
001| 
001| Commands:
001|     enc         do_encode           - Encode a message (using files)
001|     dec         do_decode           - Decode a message (using files)
001| 
001|     A5          do_test_AAAAA       - Encode/Decode 'AAAAA'
001|     alpha       do_test_alphabet    - Encode/Decode Alphabet (UC)
001|     msg1        do_test_msg_1       - Encode/Decode TestMessage1
001|     msg2        do_test_msg_2       - Encode/Decode TestMessage2
001|     block       do_test_block       - Encode/Decode LOTS of 'A's
001| 
001|     make        do_make_wheelpack   - Generate a new WheelPack
001|     list        do_list_wheelpack   - List the current WheelPack
001|     wheel       do_test_wheel       - Test a specific wheel
001| 
001|     test        do_test             - Test
001|     cset        do_list_charsets    - List Character Sets
001| 
001| '''

002| ####################################################################################################
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path
006| from random import shuffle
007| from json import dump,dumps, load,loads
008| from logger import logger,info,debug,trace, LogFilenameTimestamp
009| from goodies import KWARG, typename, triplets_left
010| from files import fileobj, linefile
011| ####################################################################################################
012| BasePath = r'C:\CJS\prj\Python\app\sims\enigma'
013| Log = logger('Enigma')
014| 
015| CMND = ''
016| ARGS = {
017|     #'wn': 'full',
018|     #'wlist': 'w0007,w0008,w0009',
019|     #'msgpath': BasePath, # original message
020|     #'msgname': 'enigma-msg.in',
021|     #'encpath': BasePath, # encrypted message
022|     #'encname': 'enigma-enc.out',
023|     #'txtpath': BasePath, # decrypted message
024|     #'txtname': 'enigma-out.out',
025|     #'fpath': BasePath, # output files
026|     #'fname': 'enigma.out',
027|     #'wpath': BasePath, # wheel database file
028|     #'wname': 'enigma-wheels.json',
029| }
030| 
031| ##------------------------------------------------------------------------------------------------##
032| AlphaUC = [chr(ord('A')+n) for n in range(26)]
033| AlphaLC = [chr(ord('a')+n) for n in range(26)]
034| Numbers = [chr(ord('0')+n) for n in range(10)]
035| 
036| CharSet = Numbers+AlphaUC+AlphaLC+['.','_']
037| FullSet = Numbers+AlphaUC+AlphaLC+[',','.',';',':','?','!','(',')',"'",'"','+','-','*','_']
038| TestSet = [chr(ord('A')+n) for n in range(8)]
039| 
040| ##------------------------------------------------------------------------------------------------##
041| '''QQx Codes Table (and reverse lookup).'''
042| QQxCodes = {
043|     ord(' '):'QQS', ord('Q'):'QQQ',
044|     ord('.'):'QQP', ord(','):'QQC', ord('?'):'QQI', ord('!'):'QQB',
045|     ord('\t'):'QQT', ord('\n'):'QQN', ord('\r'):'QQR',
046| }
047| QQxUncodes = {v:k for k,v in QQxCodes.items()}
048| 
049| ##================================================================================================##
050| '''Encode a string with QQx codes.'''
051| QQx = lambda s: s.translate(QQxCodes)
052| 
053| ##================================================================================================##
054| def unQQx (s):
055|     '''Decode a string with QQx codes.'''
056|     chars = list(s)
057|     buff = []
058|     # Scan all characters looking for QQx codes...
059|     while 0 < len(chars):
060|         ch1 = chars.pop(0)
061|         if ch1 != 'Q':
062|             buff.append(ch1)
063|             continue
064|         # Second code: QQ...
065|         ch2 = chars.pop(0)
066|         if ch2 != 'Q':
067|             raise RuntimeError('Stream contains an invalid Q. (Q%s)' % ch2)
068|         # Third code: QQx...
069|         ch3 = chars.pop(0)
070|         code = ch1+ch2+ch3
071|         if code not in QQxUncodes:
072|             raise RuntimeError('Stream contains an invalid QQx code. (%s)' % code)
073|         # Convert QQx code to character...
074|         ch = chr(QQxUncodes[code])
075|         buff.append(ch)
076| 
077|     # Return processed string...
078|     return ''.join(buff)
079| 
080| ##================================================================================================##
081| def one_then_zeros ():
082|     n = 1
083|     while True:
084|         yield n
085|         n = 0
086| 
087| ##------------------------------------------------------------------------------------------------##
088| TestMessage1 = 'Some subjects are so serious that one can only joke about them stop'
089| 
090| ##------------------------------------------------------------------------------------------------##
091| TestMessage2 = '''\
091| Another very late edition and in the same week. In this case, it is because I had not planned a Friday Notes post for today, but I have gotten so indolent lately that I am falling out of the habit of blogging. Or, the eternal question, have I perhaps gotten weary of it?
091| 
091| But, as polite people say, Stuff happens. And because it does, I have enough perishable notes that I may have to put out two Notes editions this month.
091| 
091| Assuming I can get back in the blogging habit.
091| 
091| Summer has just been too much fun. Except for the wasps. And the occasional heatwave. But we have got it pretty easy compared to some folks down south. In fact, I had the AC on last weekend because of the heatwave, but a few days ago I turned on the furnace because temps suddenly dropped into the 50s and 60s.
091| '''

092| 
093| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
094| class EnigmaWheel:
095|     '''Enigma Wheel class.
095| 
095| Instances model an Enigma wheel. The class also can generate a new Wheelpack
095| (which is a dictionary of Wheelsets, each containing the configuration for a
095| potential EnigmaWheel instance. A wheel is a bidirectional (random) map of the
095| charset. It takes the index of the char in the charset and transforms it to a
095| differerent index value. In reverse, that "output" index becomes the input and
095| the original index becomes the output.
095| 
095| Class Methods:
095|     .LoadLib        - public: Load the current Wheelpack library
095|     .MakeLib        - public: Creates a new Wheelpack library
095|                       (Careful: Overwrites current library!)
095|     .MakeSet        - private: Creates a new Wheelset
095|     .MakeWheel      - private: Creates a new Wheel configuration
095| 
095| Instance Methods:
095|     .encode (ch)        - encode a character
095|     .decode (ch)        - decode a character
095|     .fwd (cx)           - encode a character index
095|     .rev (cx)           - decode a character index
095| 
095|     .reset ()           - reset wheel to starting state
095|     .turn ()            - turn the wheel (sets .carry on roll-over)
095|     .find (ch, col)     - private: find a character on the wheel
095| 
095|     len(obj)            - length of charset (and cmap and rmap)
095|     iter(obj)           - iterator over rmap
095|     obj[name]           - get an rmap item (read/only)
095| '''

096|     Lib = {}
097|     LibName = 'enigma-wheels.json'
098|     LibPath = BasePath
099| 
100|     def __init__ (self, gid, wid):
101|         '''New EnigmaWheel instance.'''
102|         self.gid = gid
103|         self.wid = wid
104|         self.cs = EnigmaWheel.Lib[gid]['cs']
105|         self.cfg = EnigmaWheel.Lib[gid][wid]
106|         self.reset()
107| 
108|     def reset (self):
109|         '''Reset the Wheel to its initial state.'''
110|         self.rotation = 0
111|         self.carry = 0
112|         # Generate wire indexes...
113|         self.cmap = list(self.cs)
114|         self.rmap = [self.cs[self.cfg[k]] for k in sorted(self.cfg)]
115|         self.wheel = list(zip(self.cmap, self.rmap, one_then_zeros()))
116| 
117|     def find (self, ch, col=0):
118|         '''Find a given character on the wheel.'''
119|         assert ch in self.cmap
120|         assert 0 <= col <= 2
121|         for ix,spoke in enumerate(self.wheel):
122|             if spoke[col] == ch:
123|                 return ix
124|         raise RuntimeError('Character not found. ([%d]%s)' % (col,ch))
125| 
126|     def encode (self, ch):
127|         '''Encode a single character.'''
128|         cxi = self.cs.index(ch)
129|         cxo = self.fwd(cxi)
130|         return self.cs[cxo]
131| 
132|     def decode (self, ch):
133|         '''Decode a single character. (Use wheel in reverse.)'''
134|         cxi = self.cs.index(ch)
135|         cxo = self.rev(cxi)
136|         return self.cs[cxo]
137| 
138|     def fwd (self, cxi):
139|         '''Index through the wheel. {cx-in => cx-out}'''
140|         cho = self.wheel[cxi][0]
141|         cxo = self.find(cho, col=1)
142|         return cxo
143| 
144|     def rev (self, cxi):
145|         '''Index through the wheel in reverse.'''
146|         cho = self.wheel[cxi][1]
147|         cxo = self.find(cho, col=0)
148|         return cxo
149| 
150|     def turn (self):
151|         '''Turn the wheel one notch.'''
152|         Log.trace('%s[%d]: Turn!' % (self.wid, self.rotation))
153|         self.wheel.append(self.wheel.pop(0))
154|         self.rotation += 1
155|         self.carry = self.wheel[0][2]
156|         Log.trace('%s[%d]: Turned!' % (self.wid, self.rotation))
157|         return self.carry
158| 
159|     def __len__ (self): return len(self.wheel)
160|     def __iter__ (self): return iter(self.wheel)
161|     def __getitem__ (self, cx): return self.wheel[cx]
162|     def __setitem__ (self, cx, valu): raise NotImplementedError('Do not attempt to rewire the wheel!')
163|     def __delitem__ (self, cx): raise NotImplementedError('Do not attempt to rewire the wheel!')
164| 
165|     def __str__ (self):
166|         '''Prints a list of the mappings.'''
167|         ws = ''.join(['%s%s' % (f,r) for f,r,c in self])
168|         return '%s[%d](%d) %s' % (self.wid,len(self),self.rotation,ws)
169| 
170|     def __repr__ (self):
171|         '''JSON String.'''
172|         rs = ','.join(['%d:"%s"' % (ix,n) for ix,n in enumerate(self.rmap)])
173|         t = (typename(self), self.wid, len(self), self.rotation, self.carry, rs)
174|         s = '{%s:{id:"%s", len:%d, rot:%d, carry:%d, rmap:[%s]}}'
175|         return s % t
176| 
177|     @classmethod
178|     def LoadLib (cls, fname=None, fpath=None):
179|         '''Load a library for encoding and decoding.'''
180|         filename = fname if fname else EnigmaWheel.LibName
181|         filepath = fpath if fpath else EnigmaWheel.LibPath
182|         fn = path.join(filepath, filename) if filepath else filename
183|         fp = open(fn, mode='r', encoding='utf8')
184|         try:
185|             wheelpack = load(fp)
186|         except:
187|             raise
188|         finally:
189|             fp.close()
190|             Log.info('loaded: %s' % fn)
191|             Log.info()
192|         cls.Lib.clear()
193|         # For each set in the pack...
194|         for wsn in sorted(wheelpack):
195|             #Log.trace('WheelSet[%s]' % wsn)
196|             charset = wheelpack[wsn]['cs']
197|             wireset = wheelpack[wsn]['ws']
198|             cls.Lib[wsn] = {'cs':charset}
199|             # For each wheel in the set...
200|             for wn in wireset:
201|                 Log.trace(' Wheel[%s]' % wn)
202|                 wheel = wireset[wn]
203|                 cls.Lib[wsn][wn] = {}
204|                 # For each wire on the wheel...
205|                 for wire in wheel:
206|                     Log.trace(' Wire[%s]=%s' % (wire,wheel[wire]))
207|                     wconn = wheel[wire]
208|                     cls.Lib[wsn][wn][int(wire)] = int(wconn)
209|                 Log.trace()
210|             Log.trace()
211|         return wheelpack
212| 
213|     @classmethod
214|     def MakeLib (cls, names, charsets, size=9, fname=None, fpath=None):
215|         '''Generate a new WheelPack.'''
216|         Log.debug('Enigma::MakeLib: nsets=%d nwheels=%d' % (len(names),size))
217|         # Generate a wheelset for each charset...
218|         wss = {}
219|         for nm,cs in zip(names,charsets):
220|             ws = cls.MakeSet('w%04d', cs, size=size)
221|             wss[nm] = {'cs':cs, 'ws':ws}
222|         # Write the wheelpack to file...
223|         filename = fname if fname else EnigmaWheel.LibName
224|         filepath = fpath if fpath else EnigmaWheel.LibPath
225|         fn = path.join(filepath, filename) if filepath else filename
226|         fp = open(fn, mode='w', encoding='utf8')
227|         try:
228|             dump(wss, fp, indent=4)
229|         except:
230|             raise
231|         finally:
232|             fp.close()
233|             Log.info('wrote: %s' % fn)
234|         return wss
235| 
236|     @classmethod
237|     def MakeSet (cls, name, charset, size=9):
238|         '''Generate a Wheelset. (A set of wheels, man!)'''
239|         Log.debug('Enigma::MakeSet: name="%s" nwheels=%d' % (name%0,size))
240|         ws = {}
241|         for ix in range(size):
242|             n = name % (ix+1)
243|             ws[n] = cls.MakeWheel(n, charset)
244|         return ws
245| 
246|     @classmethod
247|     def MakeWheel (cls, name, charset):
248|         '''Generate a wheel for a given charset.'''
249|         Log.debug('Enigma::MakeWheel: name="%s" cslen=%d' % (name,len(charset)))
250|         wires = {}
251|         # Generate indexes...
252|         wire_in_indexes = list(range(len(charset)))
253|         wire_out_indexes = list(range(len(charset)))
254|         # Scramble them...
255|         shuffle(wire_in_indexes)
256|         shuffle(wire_out_indexes)
257|         # Consume them into wires...
258|         while len(wire_in_indexes):
259|             c1 = wire_in_indexes.pop()
260|             c2 = wire_out_indexes.pop()
261|             wires[c1] = c2
262|         #Log.trace('wires=%s' % str(wires))
263|         return wires
264| 
265| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
266| class EnigmaPlugBoard:
267|     '''Enigma PlugBoard class. Swaps characters.'''
268|     def __init__ (self, plugs):
269|         '''Initialize a new EnigmaPlugBoard instance.'''
270|         self.pairs = plugs.replace(' ','').split(',')
271|         self.plugs0 = dict([p.split(':') for p in self.pairs])
272|         self.plugs1 = {v:k for k,v in self.plugs0.items()}
273|         self.counts = {k:0 for k in (list(self.plugs0)+list(self.plugs1))}
274| 
275|     def getc (self, char):
276|         if char in self.plugs0: return self.plugs0[char]
277|         if char in self.plugs1: return self.plugs1[char]
278|         return char
279| 
280|     def __call__ (self, char_in):
281|         '''Swap character if there's a plug for it.'''
282|         char_out = self.getc(char_in)
283|         if char_in in self.counts:
284|             self.counts[char_in] += 1
285|         Log.trace('Plugboard: %s => %s' % (char_in, char_out))
286|         return char_out
287| 
288|     def __len__ (self): return len(self.plugs0)
289|     def __iter__ (self): return iter(self.plugs0)
290|     def __getitem__ (self, ch): return self.plugs0[ch]
291|     def __setitem__ (self, ch, valu): raise NotImplementedError('Do not attempt to rewire the plugboard!')
292|     def __delitem__ (self, ch): raise NotImplementedError('Do not attempt to rewire the plugboard!')
293| 
294|     def __str__ (self):
295|         ss = ['(%s--%s)'%(k,v) for k,v in self.plugs0.items()]
296|         return ', '.join(ss)
297| 
298|     def __repr__ (self):
299|         '''JSON String.'''
300|         plugs = ','.join(['"%s":"%s"' % (k,v) for k,v in self.plugs0.items()])
301|         t = (typename(self), len(self,), plugs)
302|         s = '{%s:{len:%d, plugs:[%s]}}'
303|         return s % t
304| 
305| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
306| class EnigmaReflector:
307|     '''Enigma Reflector class. mode:0=null,1=wrap,2=bend,3=dual'''
308|     topmode = 5
309| 
310|     def __init__ (self, cs, mode=1):
311|         assert isinstance(cs, list)
312|         assert isinstance(mode, int)
313|         assert 0 <= mode <= EnigmaReflector.topmode
314|         assert hasattr(cs, '__len__')
315|         assert (len(cs) % 2) == 0
316|         self.mode = mode
317|         self.cs = cs
318|         self.n = len(self.cs)
319|         self.m = len(self.cs) // 2
320| 
321|     def getc (self, cx):
322|         # Direct reflection: no translation...
323|         if self.mode == 0:
324|             return cx
325| 
326|         # Standard reflection: upper/lower swap...
327|         if self.mode == 1:
328|             return ((cx + self.m) % self.n)
329| 
330|         # Reverse reflection: start/end swap...
331|         if self.mode == 2:
332|             return ((self.n-1) - cx)
333| 
334|         # Alternating two reflection: swap every other...
335|         if self.mode == 3:
336|             return (cx-1) if (cx & 1) else (cx+1)
337| 
338|         # Alternating four Reflection: swap every four...
339|         if self.mode == 4:
340|             match (cx & 3):
341|                 case 0: return cx+3
342|                 case 1: return cx+1
343|                 case 2: return cx-1
344|                 case 3: return cx-3
345|             raise RuntimeError('This should never happen.')
346| 
347|         # No reflection: collapse to zero...
348|         if self.mode == 5:
349|             return 0
350| 
351|         # Unknown mode: error!
352|         raise RuntimeError('Unknown Reflector mode: %d' % self.mode)
353| 
354|     def __call__ (self, cx_in):
355|         '''Reflect character. [Metered; calls getc]'''
356|         cx_out = self.getc(cx_in)
357|         ch_in, ch_out = (self.cs[cx_in], self.cs[cx_out])
358|         Log.trace('Reflector: %d|%s => %d|%s' % (cx_in,ch_in, cx_out,ch_out))
359|         return cx_out
360| 
361|     def __str__ (self):
362|         ss = [self.cs[self.getc(cx)] for cx in range(self.n)]
363|         return ''.join(ss)
364| 
365|     def __repr__ (self):
366|         '''JSON String.'''
367|         t = (typename(self), self.n, self.m, self.mode)
368|         s = '{%s:{n:%d, m:%d, mode:%d}}'
369|         return s % t
370| 
371| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
372| class EnigmaMachine:
373|     '''Enigma Machine class.
373| Instances model an Enigma Machine.
373| 
373| Instance Methods:
373| '''

374|     underbars = True
375|     qqxcoding = False
376| 
377|     @property
378|     def cs (self):
379|         return self.wheels[0].cs
380| 
381|     def __init__ (self, gid, wids, reflmode=1, loadlib=False):
382|         '''Initialize a new EnigmaMachine instance.'''
383|         self.gid = gid
384|         self.wids = wids
385|         self.plugbd = None
386|         self.reflector = None
387|         self.wheels = []
388|         self.histogram = {}
389|         Log.debug('New EnigmaMachine instance.')
390|         Log.debug('gid(%s)' % self.gid)
391|         Log.debug('wids(%s)' % ','.join(self.wids))
392|         Log.debug()
393|         # Load WheelPack library...
394|         if loadlib:
395|             EnigmaWheel.LoadLib()
396|         # Generate Wheels for the Machine...
397|         for wid in self.wids:
398|             w = EnigmaWheel(gid=self.gid, wid=wid)
399|             self.wheels.append(w)
400|             Log.debug(w)
401|         self.reflector = EnigmaReflector(self.cs, mode=reflmode)
402|         Log.debug()
403| 
404|     def reset (self):
405|         '''Reset the Machine to its initial state.'''
406|         for w in self.wheels:
407|             w.reset()
408| 
409|     def encode_message (self, txt, fname=None, fpath=None, hist=1):
410|         '''Encode a message. Optional file-save and histogram.'''
411|         Log.debug('input: %s' % txt)
412|         Log.debug('fname="%s"' % fname)
413|         Log.debug('fpath="%s"' % fpath)
414|         Log.debug()
415|         # QQx Encoding...
416|         if self.qqxcoding:
417|             txt = QQx(txt)
418|             Log.debug('qqx-coding: %s' % txt)
419| 
420|         output = []
421|         for ix,char in enumerate(txt):
422|             # Pre-process...
423|             if self.underbars:
424|                 if char == '_': raise ValueError('Disallowed message character: _')
425|                 if char in [' ','\n']: char = '_'
426| 
427|             # ENCODE...
428|             # Plugboard (if any)...
429|             if self.plugbd:
430|                 char = self.plugbd(char)
431| 
432|             # We use character index here...
433|             assert char in self.cs, ValueError('Invalid message character: "%s"' % char)
434|             cx = self.cs.index(char)
435| 
436|             # Forwards through the wheels...
437|             for w in self.wheels:
438|                 cx = w.fwd(cx)
439| 
440|             # Reflector...
441|             cx = self.reflector(cx)
442| 
443|             # Backwards through the wheels...
444|             for w in self.wheels:
445|                 cx = w.rev(cx)
446| 
447|             # Turn the assembly of wheels...
448|             for w in self.wheels:
449|                 w.turn()
450|                 if w.carry == 0:
451|                     break
452| 
453|             # Back from the index to the character...
454|             ch = self.cs[cx]
455| 
456|             # Post-process...
457| 
458|             # Add character to output queue...
459|             output.append(ch)
460|             Log.trace('%04d: %s => %s' % (ix+1,char,ch))
461| 
462|         msg = ''.join(output)
463|         Log.debug()
464|         Log.debug('output: %s' % msg)
465|         Log.debug()
466| 
467|         # Break into letter groups (of five)...
468|         out = triplets_left(msg, group=5)
469|         nuggets = out.split()
470|         msg_rows = []
471|         while 0 < len(nuggets):
472|             row = ' '.join(nuggets[0:10])
473|             msg_rows.append(row)
474|             Log.info(row)
475|             print(row)
476|             del nuggets[0:10]
477|         Log.info()
478|         print()
479| 
480|         # Write the output to a file (if filename supplied)...
481|         if fname:
482|             fn = path.join(fpath,fname) if fpath else fname
483|             fo = linefile(fn)
484|             fo.data = msg_rows
485|             fo.save()
486|             Log.info()
487| 
488|         # Generate a histogram of the output characters...
489|         if hist:
490|             Log.info('Character Histogram:')
491|             self.histogram = {ch:0 for ch in self.cs}
492|             for ch in msg:
493|                 self.histogram[ch] += 1
494|             for ch in sorted(self.histogram):
495|                 Log.info('%s: %d' % (ch,self.histogram[ch]))
496|             Log.info()
497| 
498|         # Return the (raw) encoded message...
499|         return msg
500| 
501|     def decode_message (self, txt, fname=None, fpath=None):
502|         '''Decode a message.'''
503|         Log.debug('input: %s' % txt)
504|         Log.debug('fname="%s"' % fname)
505|         Log.debug('fpath="%s"' % fpath)
506|         Log.info()
507|         output = []
508|         for ix,char in enumerate(txt):
509|             # DECODE...
510|             # We use character index here...
511|             cx = self.cs.index(char)
512| 
513|             # Forwards (in reverse) through the wheels...
514|             for w in reversed(self.wheels):
515|                 cx = w.fwd(cx)
516| 
517|             # Reflector...
518|             cx = self.reflector(cx)
519| 
520|             # Backwards (in reverse) through the wheels...
521|             for w in reversed(self.wheels):
522|                 cx = w.rev(cx)
523| 
524|             # Turn the assembly of wheels...
525|             for w in self.wheels:
526|                 w.turn()
527|                 if w.carry == 0:
528|                     break
529| 
530|             # Back from the index to the character...
531|             ch = self.cs[cx]
532| 
533|             # Plugboard (if any)...
534|             if self.plugbd:
535|                 ch = self.plugbd(ch)
536| 
537|             # Un-pre-process...
538|             if self.underbars and (ch == '_'):
539|                 ch = ' '
540| 
541|             # Add character to output queue...
542|             output.append(ch)
543|             Log.trace('%04d: %s => %s' % (ix+1,char,ch))
544| 
545|         msg = ''.join(output)
546|         Log.debug()
547|         Log.debug('output: %s' % msg)
548|         Log.debug()
549| 
550|         # QQx Encoding...
551|         if self.qqxcoding:
552|             msg = unQQx(msg)
553|             Log.trace('qqx-coding: %s' % txt)
554|             Log.trace()
555| 
556|         # Break into letter groups (of five)...
557|         if ' ' not in msg:
558|             msg = triplets_left(msg, group=5)
559|         nuggets = msg.split()
560|         msg_rows = []
561|         while 0 < len(nuggets):
562|             row = ' '.join(nuggets[0:10])
563|             msg_rows.append(row)
564|             Log.info(row)
565|             print(row)
566|             del nuggets[0:10]
567|         Log.info()
568|         print()
569| 
570|         # Write the output to a file (if filename supplied)...
571|         if fname:
572|             fn = path.join(fpath,fname) if fpath else fname
573|             fo = linefile(fn)
574|             fo.data = msg_rows
575|             fo.save()
576|             Log.info()
577| 
578|         # Return the decoded message...
579|         return msg
580| 
581|     def __str__ (self):
582|         t = (self.gid, ','.join(self.wids))
583|         s = 'Enigma(%s:%s)'
584|         return s%t
585| 
586|     def __repr__ (self):
587|         '''JSON String.'''
588|         s1 = ','.join(self.wids)
589|         t = (typename(self), self.gid, s1)
590|         s = '{%s:{gid:"%s", wids:[%s]}}'
591|         return s % t
592| 
593| 
594| ##================================================================================================##
595| def do_list_charsets (**kwargs):
596|     '''CMND: List the character sets.'''
597|     Log.info('list-charsets:: %s' % str(list(kwargs.keys())))
598|     Log.info()
599|     out = [
600|         '%s: %s' % ('FullSet',''.join(FullSet)),
601|         '%s: %s' % ('CharSet',''.join(CharSet)),
602|         '%s: %s' % ('AlphaUC',''.join(AlphaUC)),
603|         '%s: %s' % ('AlphaLC',''.join(AlphaLC)),
604|         '%s: %s' % ('Numbers',''.join(Numbers)),
605|         '%s: %s' % ('TestSet',''.join(TestSet)),
606|         '',
607|         '%s: %s' % ('FullSet',FullSet),
608|         '%s: %s' % ('CharSet',CharSet),
609|         '%s: %s' % ('AlphaUC',AlphaUC),
610|         '%s: %s' % ('AlphaLC',AlphaLC),
611|         '%s: %s' % ('Numbers',Numbers),
612|         '%s: %s' % ('TestSet',TestSet),
613|     ]
614|     for line in out:
615|         print(line)
616|         Log.info(line)
617|     print()
618|     Log.info()
619| 
620|     Log.info()
621|     return 'Done'
622| 
623| ##================================================================================================##
624| def do_make_wheelpack (**kwargs):
625|     '''CMND: Make WheelPack and write it to file. CAREFUL! OVERWRITES EXISTING LIBRARY!'''
626|     wpath = KWARG('wpath', EnigmaWheel.LibPath, str, kwargs)
627|     wname = KWARG('wname', EnigmaWheel.LibName, str, kwargs)
628|     num_w = KWARG('n', 9, int, kwargs)
629|     Log.info('make-wheelpack:: %s' % str(list(kwargs.keys())))
630|     Log.debug('wpath="%s"' % wpath)
631|     Log.debug('wname="%s"' % wname)
632|     Log.debug('number-of-wheels=%d' % num_w)
633|     Log.info()
634| 
635|     # Rename any existing file...
636|     fn = path.join(wpath,wname) if wpath else wname
637|     fo = fileobj(fn)
638|     if fo.xflag:
639|         assert fo.fflag
640|         from os import rename
641|         from goodies import TS
642|         Log.warn('Wheel DB file already exists: %s' % fn)
643|         Log.warn('Renaming...')
644|         s0,s1 = path.splitext(fn)
645|         alt_fn = '%s_%s%s' % (s0,TS(),s1)
646|         rename(fn, alt_fn)
647| 
648|     lib_names = ['demo', 'full', 'char']
649|     lib_chars = [AlphaUC, FullSet, CharSet]
650|     EnigmaWheel.MakeLib(lib_names, lib_chars, size=num_w, fname=wname, fpath=wpath)
651| 
652|     pack_names = list(sorted(EnigmaWheel.Lib))
653|     Log.info('Packages: %s' % ','.join(EnigmaWheel.Lib.keys()))
654| 
655|     Log.info()
656|     return 'Done'
657| 
658| ##================================================================================================##
659| def do_list_wheelpack (**kwargs):
660|     '''CMND: List WheelPack.'''
661|     fpath = KWARG('fpath', BasePath, str, kwargs)
662|     fname = KWARG('fname', 'enigma-wheels.list', str, kwargs)
663|     Log.info('list-wheelpack:: %s' % str(list(kwargs.keys())))
664|     Log.debug('fpath="%s"' % fpath)
665|     Log.debug('fname="%s"' % fname)
666|     Log.info()
667|     filename = path.join(fpath,fname) if fpath else fname
668|     output = linefile(filename)
669| 
670|     EnigmaWheel.LoadLib()
671|     filename = path.join(BasePath, EnigmaWheel.LibName)
672|     output.data.append('LibraryFilename: "%s"' % filename)
673|     output.data.append('')
674|     Log.info('LibraryFilename: "%s"' % filename)
675|     Log.info()
676| 
677|     pack_names = list(sorted(EnigmaWheel.Lib))
678|     for gname in pack_names:
679|         group = EnigmaWheel.Lib[gname]
680|         css = ''.join(group['cs'])
681|         output.data.append('GROUP: "%s"' % gname)
682|         output.data.append('> Charset: %s' % css)
683|         output.data.append('> Length: %d' % len(css))
684|         output.data.append('> Wheels: %d' % len(group))
685|         output.data.append('')
686|         Log.info('GROUP: "%s"' % gname)
687|         Log.info('> Charset: %s' % css)
688|         Log.info('> Length: %d' % len(css))
689|         Log.info('> Wheels: %d' % len(group))
690|         Log.info()
691| 
692|         wheel_names = list(sorted(group))
693|         for wname in wheel_names:
694|             if wname == 'cs': continue # skip charset
695|             wires = group[wname]
696|             wss = ','.join([('%02d'%int(wires[w])) for w in sorted(wires)])
697|             output.data.append('> Wheel: %s' % wname)
698|             output.data.append('> %s' % wss)
699|             output.data.append('')
700|             Log.info('> Wheel: %s' % wname)
701|             Log.info('> %s' % wss)
702|             Log.info()
703| 
704|         output.data.append('')
705|         Log.info()
706| 
707|     output.data.append('')
708|     Log.info()
709| 
710|     output.data.append('')
711|     output.save()
712|     Log.info()
713|     return 'Done'
714| 
715| ##================================================================================================##
716| def do_test_wheel (**kwargs):
717|     '''CMND: Test a specific wheel.'''
718|     fpath = KWARG('fpath', BasePath, str, kwargs)
719|     fname = KWARG('fname', 'wheel.out', str, kwargs)
720|     gid = KWARG('gid', 'char', str, kwargs)
721|     wid = KWARG('wid', 'w0001', str, kwargs)
722|     Log.info('test-wheel:: %s' % str(list(kwargs.keys())))
723|     Log.debug('fpath="%s"' % fpath)
724|     Log.debug('fname="%s"' % fname)
725|     Log.debug('wheel-group="%s"' % gid)
726|     Log.debug('wheel-name="%s"' % wid)
727|     Log.info()
728|     filename = path.join(fpath,fname) if fpath else fname
729|     output = linefile(filename)
730| 
731|     EnigmaWheel.LoadLib()
732|     w = EnigmaWheel(gid, wid)
733|     output.data.append('Wheel-Group: %s' % gid)
734|     output.data.append('Wheel-Name: %s' % wid)
735|     output.data.append('')
736|     output.data.append('CMap: %s' % ''.join(w.cmap))
737|     output.data.append('RMap: %s' % ''.join(w.rmap))
738|     output.data.append('')
739|     output.data.append('Wheel: %s' % ','.join(['%s%s'%(f,r) for f,r,c in w]))
740|     output.data.append('')
741| 
742|     def dump_wheel ():
743|         output.data.append(str(w))
744|         output.data.append('')
745|         Log.info(w)
746|         Log.info()
747|         for ix,ch0 in enumerate(w.cs):
748|             ch1 = w.encode(ch0)
749|             ch2 = w.decode(ch1)
750|             ccm = w.wheel[ix][0]
751|             crm = w.wheel[ix][1]
752|             m2c = w.find(ccm, col=1)
753|             m2r = w.find(crm, col=0)
754|             t = (ix, ch0,ch1,ch2, ccm,crm, m2c,m2r)
755|             fmt = '%3d: %s => %s => %s (%s,%s; %s,%s)'
756|             output.data.append(fmt % t)
757|             Log.info(fmt % t)
758|         output.data.append('')
759|         Log.info()
760| 
761|     dump_wheel()
762|     w.turn()
763|     dump_wheel()
764|     w.turn()
765|     dump_wheel()
766|     w.turn()
767|     dump_wheel()
768|     w.turn()
769|     dump_wheel()
770|     w.turn()
771|     dump_wheel()
772| 
773|     output.data.append(repr(w))
774|     output.data.append('')
775|     output.save()
776|     Log.info()
777|     return 'Done'
778| 
779| ##================================================================================================##
780| def do_encode (**kwargs):
781|     '''CMND: Encode a message.'''
782|     msgpath = KWARG('msgpath', BasePath, str, kwargs)
783|     msgname = KWARG('msgname', 'enigma-msg.txt', str, kwargs)
784|     encpath = KWARG('encpath', BasePath, str, kwargs)
785|     encname = KWARG('encname', 'enigma-enc.txt', str, kwargs)
786|     wname = KWARG('wn', 'full', str, kwargs)
787|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
788|     wids = wlist.split(',')
789|     Log.info('encode-message:: %s' % str(list(kwargs.keys())))
790|     Log.debug('msg-path="%s"' % msgpath)
791|     Log.debug('msg-name="%s"' % msgname)
792|     Log.debug('enc-path="%s"' % encpath)
793|     Log.debug('enc-name="%s"' % encname)
794|     Log.debug('wheel-name="%s"' % wname)
795|     Log.debug('wheel-list="%s"' % wlist)
796|     Log.info()
797| 
798|     # Load message file...
799|     fn = path.join(msgpath, msgname) if msgpath else msgname
800|     fo = linefile(fn)
801|     fo.load()
802|     msgtxt = ''.join(fo.data)
803| 
804|     # Encode message...
805|     tm = EnigmaMachine(wname, wids, loadlib=True)
806|     out = tm.encode_message(msgtxt, fname=encname, fpath=encpath)
807| 
808|     Log.info(tm)
809|     for w in tm.wheels:
810|         Log.info(w)
811|     Log.info()
812|     return 'Done'
813| ##================================================================================================##
814| def do_decode (**kwargs):
815|     '''CMND: Decode a message.'''
816|     encpath = KWARG('encpath', BasePath, str, kwargs)
817|     encname = KWARG('encname', 'enigma-out.txt', str, kwargs)
818|     txtpath = KWARG('txtpath', BasePath, str, kwargs)
819|     txtname = KWARG('txtname', 'enigma-enc.txt', str, kwargs)
820|     wname = KWARG('wn', 'full', str, kwargs)
821|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
822|     wids = wlist.split(',')
823|     Log.info('decode-message:: %s' % str(list(kwargs.keys())))
824|     Log.debug('enc-path="%s"' % encpath)
825|     Log.debug('enc-name="%s"' % encname)
826|     Log.debug('txt-path="%s"' % txtpath)
827|     Log.debug('txt-name="%s"' % txtname)
828|     Log.debug('wheel-name="%s"' % wname)
829|     Log.debug('wheel-list="%s"' % wlist)
830|     Log.info()
831| 
832|     # Load message file...
833|     fn = path.join(encpath, encname) if encpath else encname
834|     fo = linefile(fn)
835|     fo.load()
836|     enctxt = ''.join(fo.data).replace(' ','')
837| 
838|     # Encode message...
839|     tm = EnigmaMachine(wname, wids, loadlib=True)
840|     out = tm.decode_message(enctxt, fname=txtname, fpath=txtpath)
841| 
842|     Log.info(tm)
843|     for w in tm.wheels:
844|         Log.info(w)
845|     Log.info()
846|     return 'Done'
847| 
848| ##================================================================================================##
849| def do_test_msg_1 (**kwargs):
850|     '''CMND: Do a test using TestMessage1.'''
851|     fpath = KWARG('fpath', BasePath, str, kwargs)
852|     fname = KWARG('fname', 'enigma-msg-1.out', str, kwargs)
853|     wname = KWARG('wn', 'char', str, kwargs)
854|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
855|     wids = wlist.split(',')
856|     Log.info('test-Msg-1:: %s' % str(list(kwargs.keys())))
857|     Log.debug('fpath="%s"' % fpath)
858|     Log.debug('fname="%s"' % fname)
859|     Log.debug('wheel-name="%s"' % wname)
860|     Log.debug('wheels=[%s]' % wids)
861|     Log.info()
862| 
863|     tm = EnigmaMachine(wname, wids, loadlib=True)
864|     enc = tm.encode_message(TestMessage1, fname=fname, fpath=fpath, hist=0)
865|     tm.reset()
866|     out = tm.decode_message(enc)
867| 
868|     Log.info(tm)
869|     for w in tm.wheels:
870|         Log.info(w)
871|     Log.info()
872|     return 'Done'
873| ##================================================================================================##
874| def do_test_msg_2 (**kwargs):
875|     '''CMND: Do a test using TestMessage2.'''
876|     fpath = KWARG('fpath', BasePath, str, kwargs)
877|     fname = KWARG('fname', 'enigma-msg-2.out', str, kwargs)
878|     wname = KWARG('wn', 'full', str, kwargs)
879|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
880|     wids = wlist.split(',')
881|     Log.info('test-Msg-2:: %s' % str(list(kwargs.keys())))
882|     Log.debug('fpath="%s"' % fpath)
883|     Log.debug('fname="%s"' % fname)
884|     Log.debug('wheel-name="%s"' % wname)
885|     Log.debug('wheels=[%s]' % wids)
886|     Log.info()
887| 
888|     tm = EnigmaMachine(wname, wids, loadlib=True)
889|     enc = tm.encode_message(TestMessage2, fname=fname, fpath=fpath, hist=0)
890|     tm.reset()
891|     out = tm.decode_message(enc)
892| 
893|     Log.info(tm)
894|     for w in tm.wheels:
895|         Log.info(w)
896|     Log.info()
897|     return 'Done'
898| ##================================================================================================##
899| def do_test_alphabet (**kwargs):
900|     '''CMND: Do a test using the alphabet.'''
901|     fpath = KWARG('fpath', BasePath, str, kwargs)
902|     fname = KWARG('fname', 'enigma-alpha.out', str, kwargs)
903|     wname = KWARG('wn', 'char', str, kwargs)
904|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
905|     wids = wlist.split(',')
906|     Log.info('test-Alphabet:: %s' % str(list(kwargs.keys())))
907|     Log.debug('fpath="%s"' % fpath)
908|     Log.debug('fname="%s"' % fname)
909|     Log.debug('wheel-name="%s"' % wname)
910|     Log.debug('wheels=[%s]' % wids)
911|     Log.info()
912|     msg = ''.join([ch*5 for ch in Numbers+AlphaUC+AlphaLC])
913| 
914|     tm = EnigmaMachine(wname, wids, loadlib=True)
915|     tm.plugbd = EnigmaPlugBoard('0:x, A:N,B:Z,C:9,D:z, a:p,d:f,i:m,r:t,w:h')
916|     Log.info(tm.plugbd)
917| 
918|     enc = tm.encode_message(msg, fname=fname, fpath=fpath, hist=1)
919|     tm.reset()
920|     out = tm.decode_message(enc)
921| 
922|     Log.info(tm)
923|     for w in tm.wheels:
924|         Log.info(w)
925|     Log.info(tm.plugbd)
926|     Log.info()
927|     return 'Done'
928| ##================================================================================================##
929| def do_test_block (**kwargs):
930|     '''CMND: Do a test using a LONG string of AAAAA...'''
931|     fpath = KWARG('fpath', BasePath, str, kwargs)
932|     fname = KWARG('fname', 'enigma-block.out', str, kwargs)
933|     wname = KWARG('wn', 'char', str, kwargs)
934|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
935|     wids = wlist.split(',')
936|     Log.info('test-block:: %s' % str(list(kwargs.keys())))
937|     Log.debug('fpath="%s"' % fpath)
938|     Log.debug('fname="%s"' % fname)
939|     Log.debug('wheel-name="%s"' % wname)
940|     Log.debug('wheels=[%s]' % wids)
941|     Log.info()
942| 
943|     tm = EnigmaMachine(wname, wids, loadlib=True)
944|     msg = 'A' * (3 + pow(len(tm.cs), len(wids)))
945| 
946|     enc = tm.encode_message(msg, fname=fname, fpath=fpath, hist=1)
947|     tm.reset()
948|     out = tm.decode_message(enc)
949| 
950|     Log.info(tm)
951|     for w in tm.wheels:
952|         Log.info(w)
953|     Log.info()
954|     return 'Done'
955| ##================================================================================================##
956| def do_test_AAAAA (**kwargs):
957|     '''CMND: Do a test using the string AAAAA.'''
958|     wname = KWARG('wn', 'demo', str, kwargs)
959|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
960|     wids = wlist.split(',')
961|     Log.info('test-AAAAA:: %s' % str(list(kwargs.keys())))
962|     Log.debug('wheel-name="%s"' % wname)
963|     Log.debug('wheels=[%s]' % wids)
964|     Log.info()
965| 
966|     tm = EnigmaMachine(wname, wids, loadlib=True)
967|     enc = tm.encode_message('AAAAA', hist=0)
968|     tm.reset()
969|     out = tm.decode_message(enc)
970| 
971|     Log.info(tm)
972|     for w in tm.wheels:
973|         Log.info(w)
974|     Log.info()
975|     return 'Done'
976| 
977| ##================================================================================================##
978| def do_test (**kwargs):
979|     '''CMND: Do a test.'''
980|     fpath = KWARG('fpath', BasePath, str, kwargs)
981|     fname = KWARG('fname', 'enigma-test.txt', str, kwargs)
982|     msgpath = KWARG('msgpath', BasePath, str, kwargs)
983|     msgname = KWARG('msgname', 'enigma-msg.txt', str, kwargs)
984|     encpath = KWARG('encpath', BasePath, str, kwargs)
985|     encname = KWARG('encname', 'enigma-enc.txt', str, kwargs)
986|     txtpath = KWARG('txtpath', BasePath, str, kwargs)
987|     txtname = KWARG('txtname', 'enigma-out.txt', str, kwargs)
988|     wname = KWARG('wn', 'char', str, kwargs)
989|     wlist = KWARG('wlist', 'w0001,w0002,w0003', str, kwargs)
990|     wids = wlist.split(',')
991|     Log.info('test:: %s' % str(list(kwargs.keys())))
992|     Log.debug('filepath="%s"' % fpath)
993|     Log.debug('filename="%s"' % fname)
994|     Log.debug('msg-path="%s"' % msgpath)
995|     Log.debug('msg-name="%s"' % msgname)
996|     Log.debug('enc-path="%s"' % encpath)
997|     Log.debug('enc-name="%s"' % encname)
998|     Log.debug('txt-path="%s"' % txtpath)
999|     Log.debug('txt-name="%s"' % txtname)
1000|     Log.debug('wheel-name="%s"' % wname)
1001|     Log.debug('wheel-list=[%s]' % wids)
1002|     Log.info()
1003|     #msg = TestMessage1
1004|     msg = TestMessage2
1005|     #msg = ''.join([ch*5 for ch in Numbers+AlphaUC+AlphaLC])
1006| 
1007|     # Load message file...
1008|     #fn = path.join(msgpath,msgname) if msgpath else msgname
1009|     #fo = linefile(fn)
1010|     #fo.load()
1011|     #msg = ''.join(fo.data)
1012| 
1013|     tm = EnigmaMachine(wname, wids, loadlib=True)
1014|     tm.qqxcoding = True
1015|     tm.plugbd = EnigmaPlugBoard('0:x, A:N, B:Z, C:9, D:z, a:p, d:f, i:m, r:t, w:h')
1016|     Log.info(tm.plugbd)
1017|     Log.info()
1018| 
1019|     enc = tm.encode_message(msg, fname=encname, fpath=encpath, hist=0)
1020|     tm.reset()
1021|     #tm.plugbd = None
1022|     tm.decode_message(enc, fname=txtname, fpath=txtpath)
1023| 
1024|     Log.info(tm)
1025|     for w in tm.wheels:
1026|         Log.info(w)
1027|     Log.info(tm.plugbd)
1028|     Log.info()
1029|     return 'Done'
1030| ####################################################################################################
1031| def dispatch (cmd, **kwargs):
1032|     '''Dispatch to a module function based on CMD.'''
1033|     Log.info('CMD: %s' % cmd)
1034|     for kw in kwargs:
1035|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
1036|     Log.info()
1037|     if cmd == 'list': return do_list_wheelpack(**kwargs)
1038|     if cmd == 'enc': return do_encode(**kwargs)
1039|     if cmd == 'dec': return do_decode(**kwargs)
1040|     if cmd == 'A5': return do_test_AAAAA(**kwargs)
1041|     if cmd == 'alpha': return do_test_alphabet(**kwargs)
1042|     if cmd == 'msg1': return do_test_msg_1(**kwargs)
1043|     if cmd == 'msg2': return do_test_msg_2(**kwargs)
1044|     if cmd == 'block': return do_test_block(**kwargs)
1045|     if cmd == 'wheel': return do_test_wheel(**kwargs)
1046|     if cmd == 'cset': return do_list_charsets(**kwargs)
1047|     if cmd == 'test': return do_test(**kwargs)
1048|     if cmd == 'make': return do_make_wheelpack(**kwargs)
1049|     return 'Nothing to do!'
1050| ####################################################################################################
1051| if __name__ == '__main__':
1052|     print('autorun: %s' % argv[0])
1053|     #Log.start(path.join(BasePath,LogFilenameTimestamp('enigma_%s.log')))
1054|     Log.start(path.join(BasePath,'enigma.log'))
1055|     Log.level(info())
1056|     Log.info(argv[0])
1057|     Log.info()
1058|     cmd = argv[1] if 1 < len(argv) else CMND
1059|     kwargs = ARGS
1060|     for a in argv[2:]:
1061|         nv = a.split('=', 1)
1062|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
1063|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
1064|     try:
1065|         print('CMD: %s' % cmd)
1066|         print()
1067|         obj = dispatch(cmd, **kwargs)
1068|         print()
1069|         print(obj)
1070|         Log.info()
1071|         Log.info(obj)
1072|     except:
1073|         etype, evalue, tb = exc_info()
1074|         ts = extract_tb(tb)
1075|         Log.error()
1076|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
1077|         Log.error()
1078|         for t in ts[-5:]:
1079|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
1080|             Log.error(' %s' % t[3])
1081|             Log.error()
1082|         raise
1083|     finally:
1084|         Log.end()
1085| ####################################################################################################
1086| '''eof'''
1087|