

Task

Implement a Caesar cipher, both encoding and decoding. 

The key is an integer from 1 to 25.

This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).

The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).

So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".

This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.

Caesar cipher is identical to Vigenère cipher with a key of length 1. 

Also, Rot-13 is identical to Caesar cipher with key 13.



Related tasks

 Rot-13
 Substitution Cipher
 Vigenère Cipher/Cryptanalysis


with javascript_semantics
sequence alpha_b = repeat(0,255)
         alpha_b['A'..'Z'] = 'A'
         alpha_b['a'..'z'] = 'a'
 
function caesar(string s, integer key)
integer ch, base
    for i=1 to length(s) do
        ch = s[i]
        base = alpha_b[ch]
        if base then
            s[i] = base+remainder(ch-base+key,26)
        end if
    end for
    return s
end function
string s = "One fine day in the middle of the night, two dead men got up to fight. \n"&
           "Back to back they faced each other, drew their swords and shot each other. %^&*()[",
       e = caesar(s,5),
       r = caesar(e,26-5)  ?e ?r
