Vigenère cipher: Difference between revisions
Content added Content deleted
(Refactored code) |
|||
Line 1,244: | Line 1,244: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
|||
<lang Julia>function encrypt(msg:: |
<lang Julia>function encrypt(msg::AbstractString, key::AbstractString) |
||
⚫ | |||
msg = uppercase(join(filter(isalpha, collect(msg)))) |
|||
key = uppercase(join(filter(isalpha, collect(key)))) |
key = uppercase(join(filter(isalpha, collect(key)))) |
||
⚫ | |||
keylen = length(key) |
|||
if |
if keylen < msglen |
||
key = (key |
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen] |
||
end |
end |
||
enc = |
enc = Vector{Char}(msglen) |
||
for i |
@inbounds for i in 1:length(msg) |
||
enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65) |
enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65) |
||
end |
end |
||
join(enc) |
return join(enc) |
||
end |
end |
||
function decrypt(enc:: |
function decrypt(enc::AbstractString, key::AbstractString) |
||
enc = uppercase(join(filter(isalpha, collect(enc)))) |
enc = uppercase(join(filter(isalpha, collect(enc)))) |
||
⚫ | |||
⚫ | |||
msglen = length(enc) |
|||
key = uppercase(join(filter(isalpha, collect(key)))) |
|||
keylen = length(key) |
|||
if |
if keylen < msglen |
||
key = (key |
key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen] |
||
end |
end |
||
msg = |
msg = Vector{Char}(msglen) |
||
for i |
@inbounds for i in 1:length(enc) |
||
msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65) |
msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65) |
||
end |
end |
||
join(msg) |
return join(msg) |
||
end |
end |
||
const |
const messages = ("Attack at dawn.", "Don't attack.", "The war is over.") |
||
const key = "LEMON" |
const key = "LEMON" |
||
for msg in messages |
|||
println(encrypt(msg, key)) |
|||
enc = encrypt(msg, key) |
|||
dec = decrypt(enc, key) |
|||
println("Original: $msg\n -> encrypted: $enc\n -> decrypted: $dec") |
|||
end</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Original: Attack at dawn. |
|||
-> encrypted: LXFOPVEFRNHR |
|||
ATTACKATDAWN</pre> |
|||
-> decrypted: ATTACKATDAWN |
|||
Original: Don't attack. |
|||
-> encrypted: OSZHNEXMQX |
|||
-> decrypted: DONTATTACK |
|||
Original: The war is over. |
|||
-> encrypted: ELQKNCMECIPV |
|||
-> decrypted: THEWARISOVER</pre> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |