Caesar Cipher in Python

It’s called the Caesar Cipher, a simple encryption technique that is known to be thousands of years old. Julius Caesar used it allegedly to encode messages. The shift is made with a fixed number of positions through the alphabet letters. Let’s see what more there is in it.

Concept of Caesar Cipher

  • Encryption: Replace each letter of the plaintext by a letter some fixed number of positions down the alphabet.
  • Decryption: The reverse process of encryption is done by shifting the letters back by the same number of positions.

For instance, if the shift is 3:

  • Plain text: HELLO
  • Ciphertext: KHOOR

Key Elements

1. Shift Value:

  • The number of places that each letter have shifted.
  • It can be any integer, positive or negative.

2. Alphabet Wrapping:

  • The alphabet wraps around at the end. For example, shifting Z by 1 results in A.

3. Case Sensitivity:

  • Letters maintain their case, either uppercase or lowercase.

4. Non-Alphabet Characters:

  • Spaces, numbers, and special characters are typically left alone.

Implementation in Python

Let’s write a Python program step by step.

1. Encrypt Function

The encryption function will:

  • Shift each letter by a given number of positions.
  • Use ASCII values for shifting.

Here’s the implementation:

def caesar_encrypt(text, shift):
    result = ""
    for char in text:
        if char.isalpha():
            shift_base = ord('A') if char.isupper() else ord('a')
            # Shift character and wrap using modulo
            shifted_char = chr((ord(char) - shift_base + shift) % 26 + shift_base)
            result += shifted_char
        else:
            # Non-alphabet characters remain unchanged
            result += char
    return result

2. Decrypt Function

Decryption reverses the process by shifting the letters backward.

def caesar_decrypt(ciphertext, shift):
    # Decrypt by shifting backward
    return caesar_encrypt(ciphertext, -shift)

3. Full Example

# Caesar Cipher Example
def caesar_encrypt(text, shift):
    result = ""
    for char in text:
        if char.isalpha():
            shift_base = ord('A') if char.isupper() else ord('a')
            shifted_char = chr((ord(char) - shift_base + shift) % 26 + shift_base)
            result += shifted_char
        else:
            result += char
    return result

def caesar_decrypt(ciphertext, shift):
    return caesar_encrypt(ciphertext, -shift)

# Test the functions
plaintext = "Hello, World!"
shift = 3

# Encrypt
encrypted = caesar_encrypt(plaintext, shift)
print("Encrypted:", encrypted)

# Decrypt
decrypted = caesar_decrypt(encrypted, shift)
print("Decrypted:", decrypted)

Output:

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

Explanation of Code

1. ASCII Manipulation:

  • ord(char): Turn a character to ASCII value
  • chr(value): Return an ASCII value to the corresponding character.

2. Modulo for Wrapping:

  • ( ord(char) - shift_base + shift) % 26: Keeps values within alphabets.

3. Non-Alphabets characters handling:

  • The condition if char.isalpha() ensures only letters are encrypted.

4. Reusability:

  • Decryption reuses encryption function using a negative shift.

Customizing the Cipher

  • Negative Shifts: Allow backward shifting.
  • Variable Shifts: Use different shifts for different letters (e.g., Vigenère Cipher).
  • Case-Insensitive Mode: Convert all input to lowercase before encryption.