The Caesar Cipher

Mr. Robot
InfoSec Adventures
Published in
2 min readSep 24, 2018

The Caesar cipher, also known as the shift cipher, is a type of substitution cipher. Each letter in the plaintext is replaced with a letter a fixed number of positions to the left or right of that letter in the alphabet.

In the following example, I’m going to encrypt a message with a key of 2. This means that in order to decrypt a message, you have to shift the alphabet left or right. The key specifies how much you have to shift. Let’s take right shift decryption, for example, C becomes A and G becomes E. I think there is not much to explain the example is pretty straightforward.

Encrypted message:

UGETGV

Decrypted message:

SECRET

Source Code

If you’re not a programmer or new to programming, don’t worry I try to explain how the code works.

The encrypt(message, key) method.

The encrypt(message, key) method takes two parameters. One is your message, the other is the key. I tried to eliminate some special characters from the supplied message, but it’s far from complete. Next, the loop goes through the message character by character and if the current character is not in the alphabet, then simply append the char to the encrypted message without tampering it. I needed the index of the character in the alphabet. I used it to calculate the shifted index by adding the key to the index and using the modulo operator which gives the remainder of the division with the length of the alphabet.

C (index 2) + 3 (key) % 26 (length of the alphabet) = 5

The decrypt(message, key) method.

As you can see the decrypt(message, key) method has only one difference compared to the encrypt(message, key) method and that is the key subtraction from the letter index in the alphabet. Everything is else is exactly the same.

The Full Source Code

I created a gist on Github, so you can download and try the whole program.

Caesar cipher implementation in Python.

Feel free to download and experiment with the code!

Before you go

Thank you for taking the time to read my article. If you found it helpful, please hit the 👏 button 👏 (up to 50x) and share it to help others with similar interest find it! + Feedback is always welcome! 🙏

--

--

Mr. Robot
InfoSec Adventures

Self-taught developer with an interest in Offensive Security. I regularly play on Vulnhub and Hack The Box.