The Caesar cipher is the "hello world" of cryptography: shift every letter forward by a fixed number of places, wrapping around at the end of the alphabet. It is hopelessly insecure and completely charming, which makes it the perfect five-minute tutorial. Here it is in Scala.
Each letter is a number: A = 0, B = 1, … Z = 25.
To encrypt with a shift of k, add k, then take the result modulo 26.
To decrypt, shift by 26 - k (or just by -k and let the
modulo sort it out).
Drag the shift to slide the whole alphabet. The blue letter on top maps to the red one below it. Tap any letter to trace its mapping.
def caesar(text: String, shift: Int): String =
text.map {
case c if c.isUpper => (((c - 'A' + shift) % 26 + 26) % 26 + 'A').toChar
case c if c.isLower => (((c - 'a' + shift) % 26 + 26) % 26 + 'a').toChar
case c => c
}
val secret = caesar("Et tu, Brute?", 3) // "Hw wx, Euxwh?"
val plain = caesar(secret, -3) // "Et tu, Brute?"
The double-modulo (x % 26 + 26) % 26 is the only trick worth
remembering: it keeps the result non-negative even when shift is
negative, so the same function both encrypts and decrypts. Non-letters fall through
untouched.
Once this clicks, the natural next step is a Vigenère cipher — a Caesar cipher whose shift changes per letter according to a keyword — and from there the whole history of classical cryptanalysis opens up. But that's another five minutes.
Type anything, pick a shift, and watch it encrypt live — exactly what the Scala above does. Flip to Decrypt to run it backwards.