Python

Caesar Cipher Encryption Using Python: Step-by-Step Tutorial

Topic of Contents:

  1. How Caesar Cipher Works
  2. Caesar Cipher Encryption
  3. Step-by-Step Guide to Encrypting a Text
  4. Mathematical Expression of the Caesar Cipher Encryption
  5. What Is Modulo Operations? A Remainder Picker
  6. Conclusion
  7. Frequently Asked Questions (FAQs)

How Caesar Cipher Works

The Caesar cipher is a type of substitution cipher that involves shifting each letter of the plaintext’s fixed three number positions forward in the alphabet to generate the ciphertext. This specific shift value is referred to as the “key”. This cipher is categorized as a substitution cipher.


Alt-image & caption: Caesar Cipher – Index Numbering Value Table

Caesar Cipher Encryption

To perform an encryption with the Caesar cipher, the following is a step-by-step guide for encrypting a message using the Caesar cipher:

Step-by-Step Guide to Encrypting a Text

  1. Generate Your Plaintext Message: Begin with the plaintext message that you want to encrypt. Ensure that it consists of letters from the English alphabet.
  2. Choose a Key: Determine the key which is typically set to 3 for a standard Caesar Cipher. This key signifies how many positions each letter in the plaintext will be shifted.
  3. Encrypt the Message: For each letter in the plaintext message, perform the following steps:
    • Identify the letter’s position in the alphabet.
    • Add the key value to the letter’s position.
    • Wrap around the alphabet if necessary. If the shifted position exceeds to “Z”, loop back to the beginning of the alphabet.
    • Replace the original letter (plaintext) with the one corresponding to the new position (ciphertext).
  4. Repeat for All Letters: Continue this process for every letter in the plaintext message, shifting each one according to the key value.
  5. Collect Ciphertext: As you complete the encryption for each letter, compile the resulting letters to form the ciphertext. Once you’ve processed all letters in the plaintext message, you will have created the ciphertext which can be sent securely to the intended recipient.

Example: Let’s encrypt the word “BIMANDO” with a Caesar Cipher key of 3 using the provided table as reference:


Alt-image & caption: Caesar Cipher Encrypt “Bimando”


Alt-image & caption: Caesar Cipher Encrypt “Bimando”

So, the “BIMANDO” plaintext becomes “ELPDQGR”.

Mathematical Expression of the Caesar Cipher Encryption

Now, let’s imagine that you are a really bad hacker. You are a member of the biggest hacking team ever where you are far apart in certain locations. At a certain moment, you are planning an attack or hacking that targets a government digital service. Of course, you want a secure and confidential communication for the coordination, right? It would be ridiculous if your plans were discovered by the local authorities.

For cases like this, you definitely need encrypted messages. It takes a quite a long time if you do the encryption manually as we did previously. So, you decide to create a Python program that can encrypt a message using the Caesar cipher.

Before you implement it into a Python program, you have to be able to formulate a form of textual (mathematical) expression so that it can be processed by your program. This is where you need a formula for Caesar cipher encryption. The following is the Caesar cipher encryption mathematical expression:

E(x) = (x + k) mod 26
E(x) Denotes an Encryption of the x alphabetical index
x The index of an alphabet (plaintext)
k The “key” or shift value
mod 26 The modulo operations of the total amount of the alphabet which is 26

What Is Modulo Operations? A Remainder Picker

The easiest analogy to grasp the modulo operations concept is looking at the calculating hour time. Let’s say it is now 23:00 o’clock, and you have an appointment to meet your friends for the next three hours. What time do you make your appointment? With a simple mathematical approach, it’s simply adding 23:00 and 03:00 equal to 26:00, right? But the times don’t work like that. Instead, we add the divisor to the maximum number available in the clock which is 24, and pick up what number is left. So, 26 divided by 24 is 1, with a remainder of 2. This remainder is what we call the hour number (2 o’clock instead of 26 o’clock). It is expressed in a mathematical formula with “26 mod 24 = 2”.

Here is the trick which you should remember. When the divisor (mod value) is larger than the dividend, the number that you get is equal to the dividend. For example, the time now is 10.00 o’clock, what time is it for the next three hours? Using the modulo operations, the equation is written by (10 + 3) mod 24. Since 13 is cannot divided by 24, the result is equal to 0 with the remainder of 13. So, the answer is 13.00 o’clock. From here, we now know that the modulo operations is a remainder picker.

This concept is also applied to Caesar Cipher encryption and decryption. The total amount of the alphabet is 26 characters, starting from “A” to “Z” or “0” to “25” index. So, the formula that we use is “mod 26”.

Example: Using the previous formula, let’s encrypt the “HACKER” plaintext with the shift value of 3.


Alt-image & caption: Caesar Cipher Encryption Using Mathematical Equation

So, the ciphertext of the “HACKER” plaintext is “KDFNHU”.

Implementing Caesar Cipher in Python

Now, let’s get practical and see how to implement the Caesar cipher encryption in Python. Let’s walk through the process step by step.

Program Workflow:

  1. First, you need to have a text file that contains the message that you want to encrypt.
  2. Second, you run the program from the command line, telling it which file to use as input. For example, you might say “encrypt.py my_message.txt.”
  3. Third, the program takes the text from your file and mixes up the letters in a special way based on a shift value that you choose (by default, it’s 3). This is when the encryption process begins. It automates your cipher text generation to look like gibberish to anyone.
  4. Finally, the program then saves this encrypted message in a new file. By default, it’s named “encrypted.txt” but you can give it a different name if you want.

Caesar Cipher Encryption Python Code

1. Import the Required Library

import argparse

The code begins by importing the “argparse” library which will be used to handle the command-line arguments.

2. Caesar Cipher Function

def caesar_cipher_encrypt(text, shift):
    encrypted_text = ""
    for char in text:
        if char.isalpha():
            is_upper = char.isupper()
            char = char.lower()
            encrypted_char = chr(((ord(char) - ord('a') + shift) % 26) + ord('a'))
            if is_upper:
                encrypted_char = encrypted_char.upper()
            encrypted_text += encrypted_char
        else:
            encrypted_text += char
    return encrypted_text

This function takes two arguments: text (the input text to be encrypted) and shift (the shift value for the Caesar Cipher). It initializes an empty variable which is “encrypted_text” to store the encrypted result later. Then, iterate through each character in the input text with the following conditions:

  1. If the character is alphabetical (a letter), it performs the Caesar Cipher encryption on it while preserving the case (upper or lower).
  2. If the character is not alphabetical (e.g., space, punctuation, etc.), it leaves it unchanged and appends it to the “encrypted_text” string.

Finally, the function returns the “encrypted_text”.

3. File Input Encryption Function

def encrypt_file(input_file, output_file, shift):
    try:
        with open(input_file, 'r') as file:
            plaintext = file.read()
    except FileNotFoundError:
        print(f"Error: Input file '{input_file}' not found.")
        return

    encrypted_text = caesar_cipher_encrypt(plaintext, shift)

    try:
        with open(output_file, 'w') as file:
            file.write(encrypted_text)
        print(f"Encryption complete. Encrypted text saved to '{output_file}'.")
    except Exception as e:
        print(f"Error writing to output file: {e}")

This function takes three arguments: “input_file” (the path to the input file), “output_file” (the path to the output file where the encrypted text will be saved), and “shift” (the shift value for the Caesar cipher).

Inside the function, it attempts to open and read the content of the input file that is specified by “input_file”. If the file is not found, it shows an error message and returns it (by terminating the program). Then, it calls the “caesar_cipher_encrypt” function to encrypt the content of the input file with the specified shift.

After encryption, it attempts to open the output file that is specified by “output_file” for writing. If successful, it writes the encrypted text to the output file and prints a success message. If there’s any error while writing to the output file, it prints an error message.

4. The Main Function

def main():
    parser = argparse.ArgumentParser(description="Encrypt a text file using Caesar cipher.")
    parser.add_argument("input_file", help="Path to the input file (plaintext)")
    parser.add_argument("-o", "--output_file", default="encrypted.txt", help="Path to the output file (encrypted) [default: encrypted.txt]")
    parser.add_argument("-s", "--shift", type=int, default=3, help="Shift value for Caesar cipher [default: 3]")
    args = parser.parse_args()

    encrypt_file(args.input_file, args.output_file, args.shift)

The main function is where the program execution starts. It sets up command-line argument parsing using the “argparse” library. It defines three command-line arguments:

  • input_file (a required argument): This is the path to the input file that contains the plaintext that you want to encrypt.
  • -o or –output_file (optional argument with a default value of “encrypted.txt”): This allows you to specify the path to the output file where the encrypted text will be saved. If not provided, it defaults to “encrypted.txt”.
  • -s or –shift (optional argument with a default value of 3): This allows you to specify the shift value for the Caesar Cipher. If not provided, it defaults to a shift of 3.

The “argparse” library automatically handles parsing the command-line arguments and stores them in the “args” object.

It then calls the “encrypt_file” function with the provided input file path, output file path (or the default), and shift value (or the default).

5. Script Execution

if __name__ == "__main__":
    main()

Finally, the script checks if it’s being run as the main program using “if __name__ == “__main__”:” and calls the main function to start the program execution.

Proof of Concept

Suppose you are a leader of a hacking team and you want to send the following secret message to your members about the next operation.


Alt-image & caption: Plaintext Message

Using the Caesar cipher encryption that we we previously made, you then encrypt the message and here is the result:


Alt-image & caption: Proof of concept Caesar Cipher Python

Try It Yourself

Download this program source code on our GitHub page at https://github.com/bimando/Caesar-Cipher-Toolkit.

Conclusion

In this comprehensive guide, we =examined the mathematical expression behind the Caesar cipher encryption, highlighting the modulo operation as a critical concept for understanding its application. This operation ensures that the ciphertext remains within the bounds of the alphabet, making the decryption process possible. We also learned a step-by-step guide to implementing the Caesar cipher in Python, complete with code examples. This practical demonstration empowers you to encrypt the messages effortlessly.

Now that you have a solid understanding of the Caesar Cipher and how to use it, you can explore its potential applications in various security and cryptography scenarios. Whether for educational purposes or practical use, the Caesar Cipher remains a valuable tool in the world of encryption.

Frequently Asked Questions (FAQs)

1. What is the Caesar cipher and why is it called so?
The Caesar Cipher is a type of substitution cipher that is used for encrypting the text. It is named after Julius Caesar who is believed to have employed it to secure his military messages during ancient campaigns. The name stems from the fact that Caesar shifted each letter in the plaintext by a fixed number of positions in the alphabet known as the “key.”

2. How does the Caesar cipher work?
The Caesar cipher operates by shifting each letter in the plaintext message by a fixed number of positions in the alphabet. To encrypt a message, you select a key that represents the number of positions to shift.

3. What is the mathematical expression for Caesar cipher encryption?
The mathematical expression for Caesar cipher encryption is:

E(x) = (x + k) mod 26

Here, E(x) denotes the encryption of the “x” alphabetical index where “x” is the index of an alphabet in the plaintext, “k” is the key or shift value, and “mod 26” represents the modulo operation with 26 as the total number of alphabets.

4. What is the significance of the modulo operation in Caesar cipher encryption?
The modulo operation ensures that the resulting ciphertext remains within the bounds of the alphabet. It is crucial to prevent shifts that exceed the available letters. For example, when shifting “Z” by 3 positions, it wraps around to “A”, ensuring the encryption process remains valid.

5. How can I implement the Caesar cipher in Python?
To implement the Caesar cipher in Python, you can follow the step-by-step guide provided in this article. You need to create a Python program that takes a plaintext message and a key (shift value), and then encrypts the message using the Caesar cipher algorithm. The article includes a Python code example to help you get started.

About the author

BIMA FAJAR RAMADHAN

Penetration Tester with Kali Linux. Reach me on Facebook https://www.facebook.com/xbimando