Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Playfair Cipher by ssk8
key_fill = "abcdefghijklmnopqrstuvwxyz0123456789"
def decode(dipgraphs, key, eord=-1):
if eord == -1: dipgraphs = [dipgraphs[i*2:i*2+2] for i in range(len(dipgraphs)//2)]
get_indices, get_index = lambda k, c: [k.index(c) // 6, k.index(c) % 6], lambda l: 6*l[0]+l[1]
key = [k for i, k in enumerate(key) if k not in key[:i]]
key.extend([k for k in key_fill if k not in key])
for index, dipgraph in enumerate(dipgraphs):
i = [get_indices(key, c) for c in dipgraph]
if i[0][0] == i[1][0]:
i[0][1], i[1][1] = (i[0][1] + eord) % 6, (i[1][1] + eord) % 6
elif i[0][1] == i[1][1]:
i[0][0], i[1][0] = (i[0][0] + eord) % 6, (i[1][0] + eord) % 6
else:
i = [[i[0][0], i[1][1]],[i[1][0], i[0][1]]]
dipgraphs[index] = ''.join([key[get_index(j)] for j in i])
return ''.join(dipgraphs)
def encode(message, key):
message = [c for c in message.lower() if c in key_fill]
digraph, digraphs = [], []
for char in message:
if len(digraph) == 1:
if digraph[0] == char:
if char == 'x':digraph.append('z')
else: digraph.append('x')
digraphs.append(digraph)
digraph = [char]
else:
digraph.append(char)
digraphs.append(digraph)
digraph = []
elif not digraph: digraph.append(char)
if digraph:
if digraph == ['z']: digraph.append('x')
else: digraph.append('z')
digraphs.append(digraph)
return decode(digraphs, key, 1)
Jan. 31, 2017
Comments: