All Articles

Caesar's Cipher

The Caesar cipher is named after Julius Caesar

Julius Caesar used this cipher to communicate with his generals. It’s provably easy to crack it. But, I guess it doesn’t really matter if your enemies are illiterate.[Pieprzyk, Josef; Thomas Hardjono; Jennifer Seberry]

The folowing is a simple (and naïve) implementation of Caesar’s cipher in JavaScript. Simplicity is a priority for the reader. Enjoy!

First, we should define some methods for mapping an alphabet to a number. Pretty basic stuff.

const Alphabet = {}
Alphabet.data = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ')

Alphabet.letterToNumber = function (letter) {
  return Alphabet.data.indexOf(letter)
}

Alphabet.numberToLetter = function (number) {
  return Alphabet.data[number]
}

Encrypting

C(k,p)=(p+k)mod26C(k, p) = (p + k) \bmod 26

All we have to do to encrypt a message is for every character, shift it by kk places and take the remainder of when we divided it by the number of letters in our alphabet (26). For brevity, we’ll strip every character that our alphabet doesn’t know about.

const Caesar = {}

Caesar.encrypt = function (plainText, key) {
  const cipherText = Array.from(plainText).map(letterToNumber).filter(i => i !== -1).map(num => {
    return (num + key) % 26
  })
  
  return cipherText.map(numberToLetter).join('')
}

Decrypting

p(k,C)=(Ck)mod26p(k, C) = (C - k) \bmod 26

Decrypting a Caesar cipher is straightforward. Instead of shifting every letter to the right, we shift them to the left. We still take modulo 26.

Caesar.decrypt = function (cipherText, key) {
  const plainText = Array.from(cipherText).map(letterToNumber).map(num => {
    return (num - key) % 26
  })
  
  return plainText.map(numberToLetter).join('')
}

An easy way to crack Caesar’s cipher is to brute force it, as there are only 26 keys. This involves trying every key. However, it’s necessary to know the language of the plain text in order to identify it.