(phixonline)-->
with javascript_semantics
constant ADFGVX = "ADFGVX",
ALEPH = tagset('Z','A')&tagset('9','0')
function create_polybius()
string aleph = shuffle(ALEPH)
-- string aleph = "U1CNHFEM4RSGPI8965X2ZB7KA3YVOD0WQTJL" -- Nim
-- string aleph = "T71VB5HYG2JKIQM8REOPDUNCZ063FXAW9S4L" -- Wren
-- string aleph = "NA1C3H8TB2OME5WRPD4F6G7I9J0KLQSUVXYZ" -- wp
sequence tmp = split(join_by(aleph,1,6," "),'\n')
printf(1,"6 x 6 Polybius square:\n")
printf(1," | A D F G V X\n")
printf(1,"---------------\n")
for i=1 to length(tmp) do
printf(1,"%s | %s\n",{ADFGVX[i],tmp[i]})
end for
return aleph
end function
function lnua(string word, integer n)
return length(word)==n
and length(unique(word))==n
and length(filter(word,"in",ALEPH))==n
end function
function create_key(integer n)
assert(n>=7 and n<=12)
sequence candidates = filter(upper(unix_dict()),lnua,n)
string res = candidates[rand(length(candidates))]
-- string res = "PHAGOCYTE" -- Nim
-- string res = "SUNFLOWER" -- Wren
-- string res = "PRIVACY" -- wp
printf(1,"\nThe key is %s\n",{res})
return res
end function
function encrypt(string polybius, key, plaintext)
integer l = length(key)
sequence tags = custom_sort(key,tagset(l)),
res = ""
for i=1 to length(plaintext) do
integer k = find(plaintext[i],polybius)
if k then -- (simply ignore any non-alphanum)
res &= ADFGVX[floor((k-1)/6)+1]&
ADFGVX[remainder((k-1),6)+1]
end if
end for
res = substitute(join(columnize(split_by(res,l),tags,' '))," "," ")
return res
end function
function decrypt(string polybius, key, encrypted)
integer l = length(key)
sequence tags = custom_sort(key,tagset(l)),
tmp = columnize(split(encrypted,' '),{},' ')
tmp = trim(join(apply(true,extract,{tmp,{tags},true}),""))
string plaintext = ""
for i=1 to length(tmp) by 2 do
integer r = find(tmp[i],ADFGVX)-1,
c = find(tmp[i+1],ADFGVX)
plaintext &= polybius[r*6+c]
end for
return plaintext
end function
string polybius = create_polybius(),
key = create_key(9),
plaintext = "ATTACKAT1200AM",
encrypted = encrypt(polybius,key,plaintext),
decrypted = decrypt(polybius,key,encrypted)
printf(1,"\nPlainText : %s\n\nEncrypted : %s\n\nDecrypted : %s\n",
{plaintext, encrypted, decrypted})