Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Playfair Cipher by Tinus_Trotyl
TABLE = 'abcdefghijklmnopqrstuvwxyz0123456789'
def code_engine(message, key, process):
key = [ch for i, ch in enumerate(key) if not ch in key[:i]]
table = key + [ch for ch in TABLE if ch not in key]
message = ''.join(ch for ch in message.lower() if ch in TABLE)
cipher = []
if process == 'encode': # the encoder part
i, digraphs = 0, []
while i < len(message):
digraph = message[i:i + 2]
if len(digraph) == 1:
digraph = digraph + ('z' if digraph[0] != 'z' else 'x')
if digraph[0] != digraph[1]:
i += 2
elif digraph[0] != 'x':
digraph = digraph[0] + 'x'
i += 1
else:
digraph = digraph[0] + 'z'
i += 1
digraphs.append(digraph)
p = 1
else: # the decoder part
digraphs = [''.join(message[i:i+2]) for i in range(0, len(message), 2)]
p = 5
for digraph in digraphs:
y0, x0 = divmod(table.index(digraph[0]), 6)
y1, x1 = divmod(table.index(digraph[1]), 6)
if x0 == x1:
ecx0, ecx1 = x1, x0
ecy0, ecy1 = (y0 + p) % 6, (y1 + p) % 6
elif y0 == y1:
ecy0, ecy1 = y0, y1
ecx0, ecx1 = (x0 + p) % 6, (x1 + p) % 6
else:
ecx0, ecy0 = x1, y0
ecx1, ecy1 = x0, y1
cipher.append(table[6 * ecy0 + ecx0])
cipher.append(table[6 * ecy1 + ecx1])
return ''.join(cipher)
def encode(message, key): return code_engine(message, key, 'encode')
def decode(message, key): return code_engine(message, key, 'decode')
Nov. 29, 2018
Comments: