Encrypting Messages in Python

Caesar Cipher

While learning Python, I have worked on some interesting programming projects, but my favorite so far has been encrypting messages by using the Caesar cipher; a very popular and simple encryption technique.

The Caesar cipher takes a letter from the message that you want to encrypt, and shifts it by X number of places. So, if you had the letters “A, B, C, D, E, F”, and you wanted to shift each letter by 2, “A” would become “C”, “B” would become “D” and so on. For example, if we wanted to encrypt the word “Hi” by 4 places, the encryption message would be: “lm”.

In Python, we can create an encryption function that would take 2 inputs: the original message as a string and the number of places that we want to shift each letter. Ultimately, the function will perform a for loop going through each letter in the string and return the original message with each letter shifted by X number of places.

Here is what that function would look like in Python:

def encrypt(text,required_shift):
    out_string = ''
    text = text.lower() 
    for char in text:
        if char not in alphabet: 
            out_string = out_string + char
        else:
            alpha_index = alphabet.find(char) 
            out_string = out_string + alphabet[shift_amount(alpha_index +required_shift)]
    return out_string 

Try it out yourself with the full python code here, and let’s take a look at an example:

The string that I want to encrypt with a shift of 4 places is: “Have a nice day”. Using my encrypt function, I get:

As you can see above, I created a string with my message, and called the encrypt function with the string and number of shifts as its inputs. Note: I saved the result as the variable “shift” so that I can easily print it out. So, if I ever wanted to say, “Have a nice day” in encryption code, I could just say, “lezi e rmgi hec.”

Now, you might be wondering: “How is someone supposed to decipher the encrypted message?” Well, Python has a solution for this, and it is quite simple. All you have to do is print the encrypt function on the encrypted string (in this case “shift”). However, instead of using the number of places you want to shift by, you do the negative of it, so that it moves the letter back to its original location. Let’s take a look:

So easy! I hope you can try this encrypt function out for yourself and have fun encrypting messages in Python!

Source: code for function learned in 365 Data Science Python Programmer Bootcamp

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s