Playfair cipher: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) (Added Perl example) |
No edit summary |
||
Line 1,100: | Line 1,100: | ||
} |
} |
||
}</lang> |
}</lang> |
||
=={{header|Julia}}== |
|||
<lang julia>function playfair(key, txt, isencode=true, from = "J", to = "") |
|||
to = (to == "" && from == "J") ? "I" : to |
|||
function canonical(s) |
|||
s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "") |
|||
a = [c for c in s] |
|||
for i in 1:2:length(a)-1 |
|||
if a[i] == a[i + 1] |
|||
a[i + 1] = 'X' |
|||
end |
|||
end |
|||
s = String(a) |
|||
return isodd(length(s)) ? s * "X" : s |
|||
end |
|||
# Translate key into an encoding 5x5 translation matrix. |
|||
keyletters = unique([c for c in canonical(key * "ABCDEFGHIJKLMNOPQRSTUVWXYZ")]) |
|||
m = reshape(keyletters[1:25], 5, 5) |
|||
# encod is a dictionary of letter pairs for encoding. |
|||
encod = Dict() |
|||
# Map pairs in same row of matrix m. |
|||
for i in 1:5, j in 1:5, k in 1:5 |
|||
if j != k |
|||
encod[m[i, j] * m[i, k]] = m[i, mod1(j + 1, 5)] * m[i, mod1(k + 1, 5)] |
|||
end |
|||
end |
|||
# Map pairs in same column of matrix m. |
|||
for j in 1:5, i in 1:5, k in 1:5 |
|||
if i != k |
|||
encod[m[i, j] * m[k, j]] = m[mod1(i + 1, 5), j] * m[mod1(k + 1, 5), j] |
|||
end |
|||
end |
|||
# Map pairs not on same row or same column. |
|||
for (i1, j1, i2, j2) in [(a, b, c, d) for a in 1:5, b in 1:5, c in 1:5, d in 1:5] |
|||
if i1 != i2 && j1 != j2 |
|||
encod[m[i1, j1] * m[i2, j2]] = m[i1, j2] * m[i2, j1] |
|||
encod[m[i2, j2] * m[i1, j1]] = m[i2, j1] * m[i1, j2] |
|||
end |
|||
end |
|||
# Get array of pairs of letters from text. |
|||
canontxt = replace(canonical(txt), r"[^A-Z]" => "") |
|||
letterpairs = map(x -> canontxt[x], findall(r"(.)(?:(?!\1)(.))?", canontxt)) |
|||
if isencode |
|||
# Encode text |
|||
return join([encod[pair] for pair in letterpairs], " ") |
|||
else |
|||
# Decode text |
|||
decod = Dict((v, k) for (k, v) in encod) |
|||
return join([decod[pair] for pair in letterpairs], " ") |
|||
end |
|||
end |
|||
orig = "Hide the gold in...the TREESTUMP!!!" |
|||
println("Original: ", orig) |
|||
encoded = playfair("Playfair example", orig) |
|||
println("Encoded: ", encoded) |
|||
println("Decoded: ", playfair("Playfair example", encoded, false)) |
|||
</lang>{{out}} |
|||
<pre> |
|||
Original: Hide the gold in...the TREESTUMP!!! |
|||
Encoded: MB OD BZ DX AN EB UK MD IU XM ZK RZ IY |
|||
Decoded: HI DE TH EG OL DI NT HE TR EX ST UM PX |
|||
</pre> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |