Implementing Caesar Cipher in Python

Intro

The Caesar Cipher is one of the simplest and most widely known encryption techniques. Julius Caesar, who used it in his private correspondence, gives his name to this type of substitution cipher. It shifts each letter in the plaintext a certain number of places down or up the alphabet. For example, with a shift of 1, ‘A’ becomes ‘B’, ‘B’ turns into ‘C’, and so on.

The provided code outlines the Caesar Cipher’s encoding workflow, initially beginning with the acquisition of the plain text and shift key. Subsequently, it iterates over each letter, shifts it by the given key, and appends it to the cipher text, effectively encoding the entire message. Consequently, this brief overview emphasizes the systematic encryption process from plain text to cipher text.

How It Works

The encryption can be represented with a simple equation:

c = (x + n) mod 26

where c is the place value of the encrypted letter, x is the place value of the actual letter, and n is the number of positions we shift the letter. The mod 26 is because there are 26 letters in the English alphabet.

Decryption is the reverse process:

x = (c - n) mod 26

Python Implementation

Here’s a simple Python function that implements the Caesar Cipher. Additionally, it can both encrypt and decrypt text, depending on the shift value you provide.

def caesar_cipher(text, shift, decrypt=False):
    if decrypt:
        shift = -shift
    result = ""

    for i in range(len(text)):
        char = text[i]

        if char.isalpha(): # Check if it's an alphabetical character
            shift_amount = shift % 26

            if char.isupper():
                result += chr((ord(char) + shift_amount - 65) % 26 + 65)
            else:
                result += chr((ord(char) + shift_amount - 97) % 26 + 97)
        else:
            result += char

    return result

Usage Example

Here’s how you can use the caesar_cipher function to encrypt and decrypt a message:

# Encrypting a message
original_message = "Hello, World!"
shift_amount = 3
encrypted_message = caesar_cipher(original_message, shift_amount) 

print(f"Encrypted Message: {encrypted_message}") 
# Decrypting the message
decrypted_message = caesar_cipher(encrypted_message, shift_amount, decrypt=True)

print(f"Decrypted Message: {decrypted_message}")

Result:

Encrypted Message: Khoor, Zruog!
Decrypted Message: Hello, World!

With this simple Python function, you can explore the basics of encryption and decryption using the Caesar Cipher.