Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
partial solution in Clear category for Playfair Cipher by DiZ
from string import ascii_lowercase, digits
from functools import partial
def playfair(mode, message, key):
"""Playfair cipher (mode = 1 to encode, -1 to decode)"""
# Clean strings
key = ''.join(map(str.lower, filter(str.isalnum, key)))
message = ''.join(map(str.lower, filter(str.isalnum, message)))
# Construct translation table
table = []
for c in key + ascii_lowercase + digits:
if c not in table:
table.append(c)
# Cipher message
message += 'zx'[message[-1] == 'z']
n, cipher = 0, []
while n < len(message) - 1:
# Parse message into digraphs
a, b = message[n: n + 2]
double = a == b
n += 2 - double
b = (b + 'xz')[double + (a == b == 'x')]
# Cipher digraph indexes
(r_a, c_a) = divmod(table.index(a), 6)
(r_b, c_b) = divmod(table.index(b), 6)
if r_a == r_b: ## Same row
c_a, c_b = (c_a + mode) % 6, (c_b + mode) % 6
elif c_a == c_b: ## Same column
r_a, r_b = (r_a + mode) % 6, (r_b + mode) % 6
else: ## Rectangle
c_a, c_b = c_b, c_a
cipher += [(r_a, c_a), (r_b, c_b)]
# Assemble digraphs
return ''.join(table[r * 6 + c] for r, c in cipher)
encode, decode = partial(playfair, 1), partial(playfair, -1)
Sept. 27, 2014
Comments: