Simple Encryption. Caesar Cipher.

Caesar Cipher is one of the most basic form of encryption techniques. It substitutes the letter in the original message with a letter a certain number of positions down the alphabet.

For example, if the original message is ‘abc’, encrypting it with a key of 4 (the number of positions down the alphabet that is used to substitute each letter) would result in a new message of ‘def’.

Creating a Python code for a Caesar Cipher is easy, as it uses fundamental principles in coding such as determining the indices of characters in a string, string manipulation etc.

Let us consider the block of code below to encrypt a message.

We begin with the cipher (which I call it the reference with which we substitute the letters in the original message) in Line 5, the key (the number of positions that will be shifted) in Line 8, and the original message in Line 9. The cipher and the key needs to be shared with the recipient of the encrypted message for decoding it.

Line 12 uses a list comprehension to find the indices of each letter in the original message as stated in the key. In this case, a blank space is included in the cipher as the last element.
Line 16 then transpose the indices according to the key value. However, depending on the letter in the original message, the transposed indices may exceed the length of the cipher. Hence, there is a need to subtract these indices value with the length of the cipher.
Line 22 uses a list comprehension with an if-else condition to return the indices as it is, if the value is less than or equal to the length of the cipher. Otherwise, the length of the cipher is subtracted from it.

With the new set of indices, the new letters are obtained as a list in Line 27.
Line 31 then concatenates the list as a single string.

The screenshot below of the IPython console shows the output for each stage of the encryption process.

With the encrypted message on hand, decrypting the message is just reversing the steps described above.

The indices of the encrypted message with respect to the cipher is obtained as a list, which is then transposed based on the given key. We will need to correct the indices if any of them becomes a negative value after the transposition.

The new letters are obtained based on the corrected transposed indices, and concatenated as a single string to return the original message.

Is there any way to make the above codes more concise and elegant? Feel free to comment.

Leave a comment