Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Playfair Cipher by UFO665
import string
def symbols(key):
txt = ""
for s in key + string.ascii_lowercase + string.digits:
if s not in txt:
txt += s
return txt
def message(msg):
txt = ""
for s in msg.lower():
if s in string.ascii_lowercase + string.digits:
txt += s
return txt
def bigrams(msg):
lst = []
iPos = 0
msg = message(msg)
while iPos + 1 < len(msg):
if msg[iPos] == msg[iPos + 1]:
msg = "".join([msg[:iPos + 1], "x" if msg[iPos] != "x" else "z", msg[iPos + 1:]])
lst.append(msg[iPos:iPos + 2])
iPos += 2
if len(msg) % 2:
msg += "z" if msg[-1] != "z" else "x"
lst.append(msg[-2:])
return lst
def table(key):
lst = [[], [], [], [], [], []]
for i, s in enumerate(symbols(key)):
lst[i / 6].append(s)
return lst
def coords(lstTable, char):
for i, row in enumerate(lstTable):
if char in row:
return [i, row.index(char)]
def _encode(lstTable, bigram):
iPos1, iPos2 = coords(lstTable, bigram[0]), coords(lstTable, bigram[1])
if iPos1[0] == iPos2[0]:
return lstTable[iPos1[0]][(iPos1[1] + 1) % 6] + lstTable[iPos2[0]][(iPos2[1] + 1) % 6]
elif iPos1[1] == iPos2[1]:
return lstTable[(iPos1[0] + 1) % 6][iPos1[1]] + lstTable[(iPos2[0] + 1) % 6][iPos2[1]]
else:
return lstTable[iPos1[0]][iPos2[1]] + lstTable[iPos2[0]][iPos1[1]]
def _decode(lstTable, bigram):
iPos1, iPos2 = coords(lstTable, bigram[0]), coords(lstTable, bigram[1])
if iPos1[0] == iPos2[0]:
return lstTable[iPos1[0]][(iPos1[1] - 1) % 6] + lstTable[iPos2[0]][(iPos2[1] - 1) % 6]
elif iPos1[1] == iPos2[1]:
return lstTable[(iPos1[0] - 1) % 6][iPos1[1]] + lstTable[(iPos2[0] - 1) % 6][iPos2[1]]
else:
return lstTable[iPos1[0]][iPos2[1]] + lstTable[iPos2[0]][iPos1[1]]
def encode(msg, key):
txt = ""
lstTable = table(key)
for bigram in bigrams(msg):
txt += _encode(lstTable, bigram)
return txt
def decode(msg, key):
txt = ""
lstTable = table(key)
for bigram in bigrams(msg):
txt += _decode(lstTable, bigram)
return txt
Jan. 17, 2016