Simple Implementation of Caesar Cipher in Python

What is the Caesar Cipher?

Do you want to implement the Caesar Cipher in Python using functions and for-loops?

But wait, we will also describe what the Caesar Cipher is – this will help you understand how to solve it with functions.

Caesar Cipher
  • The Message Sender wants to send a message to the Message Receiver. Here an Emperor wants to send a message to his general out in the field.
  • A Messenger will take the encrypted message (the cipher) and transport it to the general (Message Receiver).
  • If the Enemy catches Messenger, then they do not understand the encrypted message (the cipher), and even better, then Messenger does not either.
  • When the encrypted message (the cipher) arrives at the general (Message Receiver) then they are the only ones that can decipher and understand the message.

In the video, I will walk you through all you need including how to implement it (Part 7).

Get an explanation of the code in this video.

Step 1: Describing the Caesar Cipher

Caesar Cipher Encryption

The explanation of the encryption with the Caesar Cipher.

  • Step 1: First, you need to use an encryption key (a value from 0-25). In the case above, key 3 is used. You rotate the alphabet the number of times the key says. That is, you take the first letter and put it in the back of the alphabet, repeating that the number of times the key says.
  • Step 2: Then you take the first letter of the message you want to encrypt. Let’s say you want to encrypt YOU ARE AWESOME. Then you have the original alphabet below the rotated one. Find the letter Y and see what letter is above (here B). That is, Y is encrypted to B.
  • Step 3: Repeat Step 2 until you have the encrypted message. You should end up with the message BRX DUH DZHVRPH.
Caesar Cipher Decryption

You should see some similarities between encryption and decryption. The difference is how the encryption/decryption arrow points in Step 2.

If we take the encrypted message (the cipher) BRX DUH DZHVRPH you should end up with the original message YOU ARE AWESOME.

Step 2: Implement the encryption function

Let’s implement a helper function encrypt_char(char, key) to encrypt a single character, char, with key. What this encrypt function does, is it makes the process above for us. Hence, we have this function to do the process of encrypting one letter.

def encrypt_char(char, key):
    return chr(ord('A') + (ord(char) - ord('A') + key) % 26)
Caesar cipher encryption breakdown

Then we can implement encrypt_message(message, key), which uses the helper function. Hence, this function below is the process of encrypting a whole message.

def encrypt_message(message, key):
    message = message.upper()
    cipher = ''
    for char in message:
        if char not in ' ,.':
            cipher += encrypt_char(char, key)
        else:
            cipher += char
    return cipher

Let’s try it.

encrypt_message("you are awesome.", 3)

Which results in BRX DUH DZHVRPH.

Step 3: Implement the decryption function

This is quite similar.

def decrypt_char(char, key):
    return chr(ord('A') + (ord(char) - ord('A') + 26 - key) % 26)
def decrypt_message(cipher, key):
    cipher = cipher.upper()
    message = ''
    for char in cipher:
        if char not in ' ,.':
            message += decrypt_char(char, key)
        else:
            message += char
    return message

Let’s try it.

decrypt_message('BRX DUH DZHVRPH.', 3)

Then you get YOU ARE AWESOME.

Bonus: Hacking the Caesar Cipher

There are only 26 possible keys, which makes a brute-force attack easy to make.

Actually, we will re-use most of the code.

def decrypt_char(char, key):
    return chr(ord('A') + (ord(char) - ord('A') + 26 - key) % 26)
def decrypt_message(cipher, key):
    cipher = cipher.upper()
    message = ''
    for char in cipher:
        if char not in ' ,.':
            message += decrypt_char(char, key)
        else:
            message += char
    return message
def hacking(cipher):
    for key in range(26):
        message = decrypt_message(cipher, key)
        print(key, message)

Let’s try it.

hacking("BRX DUH DZHVRPH")

Which will give the following output.

0 BRX DUH DZHVRPH
1 AQW CTG CYGUQOG
2 ZPV BSF BXFTPNF
3 YOU ARE AWESOME
4 XNT ZQD ZVDRNLD
5 WMS YPC YUCQMKC
6 VLR XOB XTBPLJB
7 UKQ WNA WSAOKIA
8 TJP VMZ VRZNJHZ
9 SIO ULY UQYMIGY
10 RHN TKX TPXLHFX
11 QGM SJW SOWKGEW
12 PFL RIV RNVJFDV
13 OEK QHU QMUIECU
14 NDJ PGT PLTHDBT
15 MCI OFS OKSGCAS
16 LBH NER NJRFBZR
17 KAG MDQ MIQEAYQ
18 JZF LCP LHPDZXP
19 IYE KBO KGOCYWO
20 HXD JAN JFNBXVN
21 GWC IZM IEMAWUM
22 FVB HYL HDLZVTL
23 EUA GXK GCKYUSK
24 DTZ FWJ FBJXTRJ
25 CSY EVI EAIWSQI

And we see the decrypted message at key 3, as expected.

Note: The Caesar Cipher was “secure” back at the time of Caesar

Back when the Caesar Cipher was used the theory of security was not evolved that far. And the security of the Caesar Cipher lies in the fact that the enemy (the attacker) does not know the encryption algorithm. That is, the enemy cannot make the above brute force attack, as she doesn’t know how the encryption or decryption is made.

Therefore you can say that at the time of Caesar the Caesar Cipher was secure.

What next?

I am happy you asked.

If this is something you like and you want to get started with Python, then this is part of an 8 hours FREE video course with full explanations, projects on each level, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • 2 FREE eBooks to support your Python learning.

See the full FREE course page here.

Learn Python

Learn Python A BEGINNERS GUIDE TO PYTHON

  • 70 pages to get you started on your journey to master Python.
  • How to install your setup with Anaconda.
  • Written description and introduction to all concepts.
  • Jupyter Notebooks prepared for 17 projects.

Python 101: A CRASH COURSE

  1. How to get started with this 8 hours Python 101: A CRASH COURSE.
  2. Best practices for learning Python.
  3. How to download the material to follow along and create projects.
  4. A chapter for each lesson with a descriptioncode snippets for easy reference, and links to a lesson video.

Expert Data Science Blueprint

Expert Data Science Blueprint

  • Master the Data Science Workflow for actionable data insights.
  • How to download the material to follow along and create projects.
  • A chapter to each lesson with a Description, Learning Objective, and link to the lesson video.

Machine Learning

Machine Learning – The Simple Path to Mastery

  • How to get started with Machine Learning.
  • How to download the material to follow along and make the projects.
  • One chapter for each lesson with a Description, Learning Objectives, and link to the lesson video.

2 thoughts on “Simple Implementation of Caesar Cipher in Python”

  1. I do not know whether it’s just me or if perhaps everybody
    else encountering problems with your website. It appears like some of the written text in your posts are running off the screen. Can somebody
    else please provide feedback and let me know if
    this is happening to them as well? This could be a issue with my web browser because I’ve had this happen before.
    Many thanks

    Reply

Leave a Comment