Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Playfair Cipher solution in 3rd party category for Playfair Cipher by sergekoval8
import numpy as np
import re
def table(key):
s, long=[],"abcdefghijklmnopqrstuvwxyz0123456789"
for ch in (key+long):
if ch not in s: s.append(ch)
matr=np.array(s)
return matr.reshape(6,6)
def transl(tab, prev,k):
out=''
for doubl in prev:
[y1], [x1] = np.where(tab == doubl[0])
[y2], [x2] = np.where(tab == doubl[1])
if y1 == y2:
x1 = (x1 + k) % 6
x2 = (x2 + k) % 6
elif x1 == x2:
y1 = (y1 + k) % 6
y2 = (y2 + k) % 6
else:
x1, x2 = x2, x1
out += tab[y1][x1]
out += tab[y2][x2]
return out
def encode(message, key):
step, prep_2 = 0, []
mes=re.sub('[ .;:,?!-]','',message.lower())
while len(mes) > step:
mes = mes[step:]
step = 1
if len(mes) == 1:
doubl = mes[0] + 'z' if mes[0] != 'z' else mes[0] + 'x'
elif mes[0] == mes[1]:
doubl = mes[0] + 'x' if mes[0] != 'x' else mes[0] + 'z'
else:
doubl = mes[0] + mes[1]
step = 2
prep_2.append(doubl)
return transl(table(key.lower()),prep_2,1)
def decode(secret_message, key):
prep_2=[secret_message[i:i+2] for i in range(0,len(secret_message),2) ]
return transl(table(key.lower()),prep_2,5)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert encode("Fizz Buzz is x89 XX.", "checkio101") == 'do2y7mt22kry94y2y2', "Encode fizz buzz"
assert decode("do2y7mt22kry94y2y2", "checkio101") == 'fizxzbuzzisx89xzxz', "Decode fizz buzz"
assert encode("How are you?", "hello") == 'ea2imb1ht0', "Encode How are you"
assert decode("ea2imb1ht0", "hello") == 'howareyouz', "Decode How are you"
assert encode("My name is Alex!!!", "alexander") == 'i1dlkxjqlexn', "Encode Alex"
assert decode("i1dlkxjqlexn", "alexander") == 'mynameisalex', "Decode Alex"
assert encode("Who are you?", "human") == 'rnvftc1jd5', "Encode WHo"
assert decode("rnvftc1jd5", "human") == 'whoareyouz', "Decode Who"
assert encode("ATTACK AT DAWN", "general") == 'ewwektewhnua', "Encode attack"
assert decode("ewwektewhnua", "general") == 'attackatdawn', "Decode attack"
Jan. 11, 2019