My daughter is learning about the Vigenère cipher in school and I was helping out (after reading the wiki). They are doing it by hand in school, but it seemed like it might be a good example to start showing her code, since it’s very tedious and error prone by hand.
Here’s a quick implementation, but it’s a little clunky for a kid to follow. In particular, the encode
→ and decode
← are just modulo addition and subtraction, but this is obfuscated by all the shifting by
'A'. The conversion from
Strings to vectors of
Char and back is also hiding the important part of that line, which is repeating the code word to match the message length.
message = "VIGENERE" codeword = "GREEN" →(a::Char,b::Char) = 'A'+((a-'A')+(b-'A'))%26 ←(a::Char,b::Char) = 'A'+((a-'A')-(b-'A')+26)%26 →(message::String,codeword::String) = String(collect(message) .→ collect(match_length(codeword,length(message)))) ←(message::String,codeword::String) = String(collect(message) .← collect(match_length(codeword,length(message)))) match_length(word,len) = (word^len)[1:len]