← all posts
Posted on Sep 15, 2022

Cipher: Atbash

Credit:

Credit: FotoRieth

“And after them the king of Sheshach shall drink.”

It might not be obvious, but Sheshach in that phrase is actually one of the earliest examples of secret code, in this case for the name: Babylon.
In this brief post I will go over Atbash, an old substitution cipher technique from around 500 B.C.

The name Atbash could deride from the story of Babel, where God confused the speech of people, as punishment for trying to build a tower all the way to heaven.

The Atbash Cipher in Rust 🦀

Ancient Hewbrew scribes are believed to have used the following technique to secretly encode some words:

  1. The Hebrew alphabet is “doubled back” on itself.
    Doing this on the Roman alphabet produces the mapping:
    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    ZYXWVUTSRQPONMLKJIHGFEDCBA
    As we can see, A is mapped to Z, B is mapped to Y, and so forth.
  2. In Hebrew, this doubling back of the alphabet, creates a direct correspondence between the first letter aleph and the last letter in the alphabet taw. The second letter beth is mapped to the next-to-last letter shin, and so forth.
  3. Hebrew scribes used this mapping to turn the word beth-beth-lamed into the word shin-shin-kaph.

Code: simple Rust implementation of the Atbash cipher.


A Simple Code Example

Let’s try to write a simple Atbash 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.

 1static ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 2static TEBAHPLA: &str = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
 3
 4fn atbash(sequence: &str) -> String {
 5    let mut res: Vec<char> = Vec::new();
 6    let chars: Vec<char> = sequence.chars().collect();
 7    for c in chars {
 8        res.push(TEBAHPLA.chars().nth(ALPHABET.find(c).unwrap()).unwrap());
 9    }
10
11    res.iter().collect::<String>()
12}
13
14fn main() {
15    println!("{}", atbash("ABC"));
16}
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21    #[test]
22    fn sample_test() {
23        assert_eq!(atbash("ABC"), "ZYX");
24    }
25}