← all posts
Posted on Sep 15, 2022

Cipher: Caesar

The Greek historian Polybius

The Greek historian Polybius

Gaius Julius Caesar needs little introduction. The Roman general and politician became dictator of Rome. He was assasinated in 44 B.C. by fellow senators who feared he was becoming too powerful .

In his book Gallic Wars, Julis Caesar describes a method of encipherment that has come to be known as The Caesar Cipher.

The Ciphering Process

The Caesar Cipher is an example of a shift cipher. The letters of a plaintext message is shifted (another word is rotated) three steps forward (to the right) .
The number of steps we shift can be treated as the key of the cipher.

If our message is based on the Roman alphabet, then the Caesar Cipher would encrypt $A \to D$, and $B \to E$. So for example, enciphering the plaintext message: $$“CAESARMUSTDIE”$$

would result in the ciphertext:

$$FDHVDUPXVWGLH$$

The deciphering process would mean reversing the shifting the ciphering process, by rotating each letter 3 (or however many steps was used during encipherment) steps back (to the left) to its regular position in the alphabet.


A Simple Code Example

Let’s try to write a simple Caesar Cipher program.

The following program makes a lot of assumptions on the input provided to the ciphering function. The program is only meant to illustrate the fundamental idea of the cipher.

 1const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
 2
 3fn encipher(message: &str) -> String {
 4    let mut ciphertext = String::new();
 5    let mut num: usize;
 6    let mut pos: usize;
 7
 8    for letter in message.chars() {
 9        if ALPHABET.contains(letter) {
10            num = ALPHABET.find(letter).unwrap();
11            pos = (num + 3) % 26;
12            ciphertext.push(ALPHABET.chars().nth(pos).unwrap());
13        }
14    }
15
16    ciphertext
17}
18
19fn main() {
20    println!("{}", encipher("CAESARMUSTDIE"));
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26
27    #[test]
28    fn encipher_test() {
29        assert_eq!(encipher("CAESARMUSTDIE"), "FDHVDUPXVWGLH");
30    }
31}