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 = {} = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ')

Alphabet.letterToNumber = function (letter) {

Alphabet.numberToLetter = function (number) {


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


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

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.