Playfair cipher: Difference between revisions

Content added Content deleted
Line 1,108: Line 1,108:
function canonical(s)
function canonical(s)
s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "")
s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "")
a = [c for c in s]
a, dupcount = [c for c in s], 0
b = deepcopy(a)
for i in 1:2:length(a)-1
for i in 1:2:length(a)-1
if a[i] == a[i + 1]
if a[i] == a[i + 1]
a[i + 1] = 'X'
splice!(b, i+1+dupcount:i+dupcount, 'X')
dupcount += 1
end
end
end
end
s = String(a)
s = String(b)
return isodd(length(s)) ? s * "X" : s
return isodd(length(s)) ? s * "X" : s
end
end
Line 1,120: Line 1,122:
# Translate key into an encoding 5x5 translation matrix.
# Translate key into an encoding 5x5 translation matrix.
keyletters = unique([c for c in canonical(key * "ABCDEFGHIJKLMNOPQRSTUVWXYZ")])
keyletters = unique([c for c in canonical(key * "ABCDEFGHIJKLMNOPQRSTUVWXYZ")])
m = reshape(keyletters[1:25], 5, 5)


m = Char.((reshape(UInt8.(keyletters[1:25]), 5, 5)'))
# encod is a dictionary of letter pairs for encoding.
# encod is a dictionary of letter pairs for encoding.
encod = Dict()
encod = Dict()

# Map pairs in same row of matrix m.
# Map pairs in same row of matrix m.
for i in 1:5, j in 1:5, k in 1:5
for i in 1:5, j in 1:5, k in 1:5
Line 1,170: Line 1,171:
<pre>
<pre>
Original: Hide the gold in...the TREESTUMP!!!
Original: Hide the gold in...the TREESTUMP!!!
Encoded: MB OD BZ DX AN EB UK MD IU XM ZK RZ IY
Encoded: BM OD ZB XD NA BE KU DM UI XM MO UV IF
Decoded: HI DE TH EG OL DI NT HE TR EX ST UM PX
Decoded: HI DE TH EG OL DI NT HE TR EX ES TU MP
</pre>
</pre>