2019-10-27_the-playfair-cipher.html


001| #:name::The Playfair Cipher
002| #:link::https://thehardcorecoder.com/2019/10/27/the-playfair-cipher/
003| #:date::2019-10-27
004| #:code::
005| class Playfair (object):
006|     '''Playfair encryption class.'''
007|     A2Z = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
008| 
009|     def __init__ (self, keyword):
010|         rs = range(5)
011|         kw = []
012| 
013|         for ch in keyword.upper():
014|             if (ch in self.A2Z) and (ch not in kw):
015|                 kw.append(ch)
016| 
017|         az = [a for a in self.A2Z if a not in kw]
018|         cs = list(reversed(kw+az))
019|         self.grid = [[[cs.pop(),r,c] for c in rs] for r in rs]
020| 
021|     def __str__ (self):
022|         a = [str(row) for row in self.grid]
023|         return '\n'.join(a)
024| 
025| #:code::
026| def encode (self, plaintext):
027|     '''Encode a message.'''
028|     # Condition the message for encoding...
029|     self.msg = self._condition(plaintext)
030| 
031|     # Find pairs of letters in the grid...
032|     self._ps = [self._find_pair(m) for m in self.msg]
033| 
034|     # Get the encoded pairs of letters...
035|     self._gs = [self._encode(p0,p1) for p0,p1 in self._ps]
036| 
037|     # Process the pairs...
038|     self.enc = [(g[0][0], g[1][0]) for g in self._gs]
039| 
040|     # Combine pairs to get (encoded) text...
041|     self.txt = ''.join([a[0]+a[1] for a in self.enc])
042| 
043|     # Returned the encoded text...
044|     return self.txt
045| 
046| #:code::
047| def decode (self, ciphertext):
048|     '''Decode a message.'''
049|     # Condition the message for decoding...
050|     self.msg = self._condition(ciphertext)
051| 
052|     # Find pairs of letters in the grid...
053|     self._ps = [self._find_pair(m) for m in self.msg]
054| 
055|     # Get the decoded pairs of letters...
056|     self._gs = [self._decode(p0,p1) for p0,p1 in self._ps]
057| 
058|     # Process the pairs...
059|     self.enc = [(g[0][0], g[1][0]) for g in self._gs]
060| 
061|     # Combine pairs to get (decoded) text...
062|     self.txt = ''.join([a[0]+a[1] for a in self.enc])
063| 
064|     # Special handling for Q...
065|     self.txt = self.txt.rstrip('Q')
066|     ix = self.txt.find('Q')
067|     while 0 < ix:
068|         if self.txt[ix-1] == self.txt[ix+1]:
069|             self.txt = self.txt[0:ix]+self.txt[ix+1:]
070|         ix = self.txt.find('Q', ix+1)
071| 
072|     # Returned the decoded text...
073|     return self.txt
074| 
075| #:code::
076| def _condition (self, message):
077|     '''Condition the message text.'''
078|     mesg = []
079|     state = 0
080|     tempc = ''
081| 
082|     for ch in message.upper():
083|         if ch.isalpha():
084|             if ch == 'J':
085|                 ch = 'I'
086|             if state:
087|                 if ch == tempc:
088|                     t = (tempc, 'Q')
089|                     mesg.append(t)
090|                     continue
091|                 t = (tempc, ch)
092|                 mesg.append(t)
093|                 state = 0
094|             else:
095|                 tempc = ch
096|                 state = 1
097|     if state:
098|         t = (tempc, 'Q')
099|         mesg.append(t)
100|     return mesg
101| 
102| #:code::
103| def _find_pair (self, pair):
104|     '''Find letter pair in grid.'''
105|     c0,c1 = pair
106|     rc0,rc1 = (0,0), (0,0)
107| 
108|     for row in self.grid:
109|         for col in row:
110|             if col[0] == c0:
111|                 rc0 = (col[1],col[2])
112|             if col[0] == c1:
113|                 rc1 = (col[1],col[2])
114| 
115|     # Return letter pair...
116|     return rc0,rc1
117| 
118| #:code::
119| def _encode (self, rc0, rc1):
120|     '''Get encoded letter pairs.'''
121|     if (rc0[0]==rc1[0]) and (rc0[1]==rc1[1]):
122|         # Same row and column...
123|         raise RuntimeError('Matching pair!')
124| 
125|     if rc0[0] == rc1[0]:
126|         # Same row...
127|         c0 = self.grid[rc0[0]][(rc0[1]+1)%5]
128|         c1 = self.grid[rc1[0]][(rc1[1]+1)%5]
129|         return c0,c1
130| 
131|     if rc0[1] == rc1[1]:
132|         # Same column...
133|         c0 = self.grid[(rc0[0]+1)%5][rc0[1]]
134|         c1 = self.grid[(rc1[0]+1)%5][rc1[1]]
135|         return c0,c1
136| 
137|     # Different row and column...
138|     c0 = self.grid[rc0[0]][rc1[1]]
139|     c1 = self.grid[rc1[0]][rc0[1]]
140|     return c0,c1
141| 
142| #:code::
143| def _decode (self, rc0, rc1):
144|     '''Get decoded letter pairs.'''
145|     if (rc0[0]==rc1[0]) and (rc0[1]==rc1[1]):
146|         # Same row and column...
147|         raise RuntimeError('Matching pair!')
148| 
149|     if rc0[0] == rc1[0]:
150|         # Same row...
151|         c0 = self.grid[rc0[0]][(rc0[1]-1)%5]
152|         c1 = self.grid[rc1[0]][(rc1[1]-1)%5]
153|         return c0,c1
154| 
155|     if rc0[1] == rc1[1]:
156|         # Same column...
157|         c0 = self.grid[(rc0[0]-1)%5][rc0[1]]
158|         c1 = self.grid[(rc1[0]-1)%5][rc1[1]]
159|         return c0,c1
160| 
161|     # Different row and column...
162|     c0 = self.grid[rc0[0]][rc1[1]]
163|     c1 = self.grid[rc1[0]][rc0[1]]
164|     return c0,c1
165| 
166| #:code::
167| def encode_message (keyword, message):
168|     '''Encode Message.'''
169|     # Get a new Playfair encoding instance...
170|     coder = Playfair(keyword)
171| 
172|     # Encode the message and return coded text...
173|     return coder.encode(message)
174| 
175| #:end:code::
176|