

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


(* Only non-accented English letters are altered here. *)
 
on caesarDecipher(txt, |key|)
    return caesarEncipher(txt, -|key|)
end caesarDecipher
 
on caesarEncipher(txt, |key|)
    set codePoints to id of txt
    set keyPlus25 to |key| mod 26 + 25
    repeat with thisCode in codePoints
        tell thisCode mod 32
            if ((it < 27) and (it > 0) and (thisCode div 64 is 1)) then ¬
                set thisCode's contents to thisCode - it + (it + keyPlus25) mod 26 + 1
        end tell
    end repeat
 
    return string id codePoints
end caesarEncipher
 
-- Test code:
set txt to "ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."
set |key| to 9
 
set enciphered to caesarEncipher(txt, |key|)
set deciphered to caesarDecipher(enciphered, |key|)
return "Text: '" & txt & ("'" & linefeed & "Key: " & |key| & linefeed & linefeed) & (enciphered & linefeed & deciphered)