The Vigenère Cipher

Mr. Robot
InfoSec Adventures
Published in
3 min readOct 9, 2018

The Vigenère cipher is a method of encrypting alphabetic text by using a series of interwoven Caesar ciphers, based on the letters of a keyword. It is a form of polyalphabetic substitution.

Let’s say we have a word “secret” and we want to encrypt with the key “key”. The length of the key (3) is obviously shorter than the length of the message (6). In this case, we repeat the key until it reaches the length of the plain message. The encryption key will be “keykey”. Our message starts with the letter “s”, which has an index of 18. Remember, counting starts from 0! Now, the letter “k” has an index of 10. If you add these two numbers, you’ll get a larger number than the length of the alphabet. To prevent this from happening, we can use the modulo operator, which gives the remainder of a division. The result is the index of the first encrypted letter in the alphabet.

(18 + 10) % 26 = 2 = letter “C”

Plain text message:

SECRET

Encrypted message:

CIABIR

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.

First, I removed the usual special characters. Then, I created a loop with the length of the message. I calculated the index of the i-th letter in the plain message by using the index() method that takes a char and returns the corresponding index in a string. Next, I needed the index of the i-th key letter. This time, I divided the i index with the modulo operator to prevent too large indexes and converted the letter to upper case.

The fun part is the calculation of the encrypted letter index. I did it exactly as I explained, added the two index and divided the result with the modulo operator to get the remainder. Finally, I appended the character from the alphabet to the encrypted message.

The decrypt(message, key) method.

The decrypt(message, key) method only differs in one thing and that is the subtraction instead of the addition. So, in order to decrypt the message we have to subtract the key letter index from the message letter index to get the index of the letter in the alphabet. I really hope it’s understandable and not too confusing.

The Full Source Code

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

Vigenere cipher implemented 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
Mr. Robot

Written by Mr. Robot

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