Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Playfair Cipher by Moff
import string
class PlayfairCipher(object):
letters = string.ascii_lowercase + string.digits
@classmethod
def prepare_plain(cls, plain):
a = [c for c in plain.lower() if c in cls.letters]
result = []
while len(a) > 1:
c1, c2 = a.pop(0), a.pop(0)
if c1 == c2:
a.insert(0, c2)
c2 = 'z' if c1 == 'x' else 'x'
result.append(c1 + c2)
if a:
c1 = a.pop(0)
result.append(c1 + ('x' if c1 == 'z' else 'z'))
return result
@classmethod
def prepare_code_table(cls, key):
result = ''
for c in key + cls.letters:
if c not in result:
result += c
return result
@classmethod
def encode_pair(cls, ct, pair, delta):
(r1, c1), (r2, c2) = (divmod(ct.index(c), 6) for c in pair)
if r1 != r2 and c1 != c2:
return ct[r1 * 6 + c2] + ct[r2 * 6 + c1]
elif r1 == r2:
return ct[r1 * 6 + (c1 + delta) % 6] + ct[r2 * 6 + (c2 + delta) % 6]
elif c1 == c2:
return ct[(r1 + delta) % 6 * 6 + c2] + ct[(r2 + delta) % 6 * 6 + c1]
return '--'
@classmethod
def encode(cls, plain, key, delta):
ct = cls.prepare_code_table(key)
return ''.join(cls.encode_pair(ct, pair, delta) for pair in cls.prepare_plain(plain))
def encode(plain, key):
return PlayfairCipher.encode(plain, key, 1)
def decode(cipher, key):
return PlayfairCipher.encode(cipher, key, -1)
Aug. 4, 2015