Vigenère cipher: Difference between revisions
Content deleted Content added
mv jq entry |
|||
Line 1,693: | Line 1,693: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia| |
{{works with|Julia|1.5}} |
||
<lang Julia> |
|||
<lang Julia>function encrypt(msg::AbstractString, key::AbstractString) |
|||
→(a::Char, b::Char, ± = +) = 'A'+((a-'A')±(b-'A')+26)%26 |
|||
msg = uppercase(join(filter(isalpha, collect(msg)))) |
|||
←(a::Char, b::Char) = →(a,b,-) |
|||
key = uppercase(join(filter(isalpha, collect(key)))) |
|||
msglen = length(msg) |
|||
keylen = length(key) |
|||
cleanup(str) = filter(a-> a in 'A':'Z', collect(uppercase.(str))) |
|||
if keylen < msglen |
|||
match_length(word, len) = repeat(word,len)[1:len] |
|||
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen] |
|||
end |
|||
function →(message::String, codeword::String, ↔ = →) |
|||
enc = Vector{Char}(msglen) |
|||
plaintext = cleanup(message) |
|||
key = match_length(cleanup(codeword),length(plaintext)) |
|||
return String(plaintext .↔ key) |
|||
enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65) |
|||
end |
|||
return join(enc) |
|||
end |
end |
||
←(message::String, codeword::String) = →(message,codeword,←) |
|||
cyphertext = "I want spearmint gum" → "Gimme!" |
|||
function decrypt(enc::AbstractString, key::AbstractString) |
|||
println(cyphertext) |
|||
enc = uppercase(join(filter(isalpha, collect(enc)))) |
|||
println(cyphertext ← "Gimme!") |
|||
key = uppercase(join(filter(isalpha, collect(key)))) |
|||
⚫ | |||
msglen = length(enc) |
|||
keylen = length(key) |
|||
if keylen < msglen |
|||
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen] |
|||
end |
|||
msg = Vector{Char}(msglen) |
|||
@inbounds for i in 1:length(enc) |
|||
msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65) |
|||
end |
|||
return join(msg) |
|||
end |
|||
const messages = ("Attack at dawn.", "Don't attack.", "The war is over.") |
|||
const key = "LEMON" |
|||
for msg in messages |
|||
enc = encrypt(msg, key) |
|||
dec = decrypt(enc, key) |
|||
println("Original: $msg\n -> encrypted: $enc\n -> decrypted: $dec") |
|||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> |
|||
<pre>Original: Attack at dawn. |
|||
"OEMZXYXQMVSQZFKAU" |
|||
-> encrypted: LXFOPVEFRNHR |
|||
"IWANTSPEARMINTGUM" |
|||
-> decrypted: ATTACKATDAWN |
|||
</pre> |
|||
Original: Don't attack. |
|||
-> encrypted: OSZHNEXMQX |
|||
-> decrypted: DONTATTACK |
|||
Original: The war is over. |
|||
-> encrypted: ELQKNCMECIPV |
|||
-> decrypted: THEWARISOVER</pre> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |