A Caesar cipher replaces each letter with one a fixed number of positions away in the alphabet. Picture two alphabetical dials: rotate the inner dial by the secret shift, then read each input letter against its replacement. With a shift of two, A becomes C and B becomes D. Someone who knows the shift can reverse the translation. section 15.4
To implement the shift for uppercase letters, subtract 'A' to get a position from 0 to 25, add the shift, and apply `mod` with the alphabet length. Add 'A' again to recover a character. Modulo wraps the end of the alphabet back to the beginning: with a shift of two, Z becomes B. Decryption subtracts the shift instead. The implementation leaves whitespace, punctuation, and other characters outside 'A':'Z' unchanged. section 15.4.1
Listing 15.6 Caesar cipher encryption and decryption
# count number of letters in the English alphabet
const n = length('A':'Z')
function caesar_encrypt(ch::Char, shift::Integer)
if ch in 'A':'Z' #1
'A' + mod((ch - 'A') + shift, n) #2
else
ch #3
end
end
function caesar_decrypt(ch::Char, shift::Integer)
if ch in 'A':'Z'
'A' + mod((ch - 'A') - shift, n)
else
ch
end
end
The Julia implementation shows the alphabet check, modulo calculation, and matching character-level encrypt and decrypt functions. section 15.4.1
Shift a whole message
Apply the character function across a string with `map`: shifting `"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"` by two produces `"VJG SWKEM DTQYP HQZ LWORU QXGT VJG NCBA FQI"`. Mapping decryption over that result restores the original message, including its spaces. section 15.4.1
The same cipher can serve as an interchangeable part of a password-keeping example. One design stores the shift in a `CaesarCipher` object implementing a shared `Cipher` interface. Another uses partial application: `caesar_encrypt(2)` returns a message-encryption function, so `"HELLO" |> caesar_encrypt(2) |> caesar_decrypt(2)` returns `"HELLO"`. In either design, the surrounding service can use a substitution cipher instead without changing its password-storage logic. section 15.6 section 15.7.1 section 15.7.3

