How to Write Your Own Caesar Cipher Encoder

Have you ever heard of the Caesar cipher?

Julius Caesar used this technique to conceal secret messages from his enemies!

The Caesar cipher is one of the most primitive encryption techniques.

The main idea behind this system is to rotate the letters an x number of positions on the alphabet.

For example, with x = 1, an ‘A’ becomes a ‘B’, a ‘C’ becomes a ‘D’ and so on.

caesar cipher

So how do we implement this in code?

Glad you asked, it turns out it’s not as hard as it looks. We are going to take advantage of the fact that letters can be represented by numbers (ASCII codes), which will make the job of rotating the letters a matter of just adding two numbers together.


Making Your Own Caesar Cipher Converter

We will start by converting an input string into an integer array:

ascii = "test"

Let’s break this down:

The chars method splits the string into an array of characters and it returns an enumerator. As a result we can call map on the array.

The map method is very useful when we want to transform all the elements of an array in some way. The return value of map is another array with the transformed elements.

Note: this syntax requires Ruby 1.9+, and it’s equivalent to:

ascii = "test" { |c| c.ord }

Since we want to turn every letter into its corresponding ASCII value, we call the ord method on every element of the array.

In our example, the output will be this:

[116, 101, 115, 116]


Rotation Time


The next step is to add the number of rotations we want. We can do this by using map again:

shifted = { |c| c + 5 }
=> [121, 106, 120, 121]

Now we can just turn the numbers back to letters, and join them, which will give us the encrypted string: { |c| c.chr }.join
=> "yjxy"

To retrieve our original string all we have to do is to apply the same procedure again, but this time shift to the left.

It’s important to shift by the same amount of positions we used originally; otherwise, we won’t recover our original data.


The Final Code & Alternative Versions

You can find the finished caesar cipher code here.

It produces all the 26 possible iterations for a given string and it also handles wrapping (the examples in the post don’t).

There is also an alternative version that uses Array#rotate

You might also like:
Ruby string formatting