Predictive Hacks

Caesar Cipher in Python

caesar cipher

Caesar Cipher is the most popular encryption technique where each letter in the original text is replaced by a letter according to the shifted alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on.

Let’s say that we shift the alphabet by 3 positions on the left. Then we get:

Alphabet:    ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shifted :    XYZABCDEFGHIJKLMNOPQRSTUVW

So, the algorithm is simple. We should replace every letter from the original text with the corresponding shifted one by taking into consideration the upper and lower case. We leave as is the characters which are out of the alphabet, like spaces, punctuations etc.

Caesar Cipher in Python 1

Caesar Cipher Code

The Caesar Cipher will take as input the original text and the key and we return the encrypted text.

def caesar_cipher(raw_text, key):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    shifted_alphabet = alphabet[26-key:]+alphabet[0:(26-key)]
    cipher_text = ""

    for i in range(len(raw_text)):
        char = raw_text[i]
        idx = alphabet.find(char.upper())
        if idx == -1:
            cipher_text = cipher_text + char
        elif char.islower():
            cipher_text = cipher_text + shifted_alphabet[idx].lower()
        else:
            cipher_text = cipher_text + shifted_alphabet[idx] 

    return(cipher_text)

Let’s see what is the encrypted text of the “The quick brown fox jumps over the lazy dog!” by taking a key=3

plain_text = "The quick brown fox jumps over the lazy dog!"
caesar_cipher(plain_text,3)
'Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald!'

Decrypt the Caesar Cipher

In order to decrypt the Caesar Cipher, we need to set as key the 26 minus the encrypted key which was 3 in our case.

caesar_cipher(caesar_cipher(plain_text,3),26-3)
'The quick brown fox jumps over the lazy dog!'

Voilà. We showed how we can encrypt and decrypt the Caesar Cipher using Python!

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

connect with sql
R

How to Connect R with SQL

Need to Connect R with SQL It is common for Data Analysts/Scientists to connect R with SQL. For that reason,

[the_ad_group id="232"]
[the_ad id="2133"]