October 13, 2024

Caesar Cipher in Python

The Caesar Cipher is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher where each letter in the plaintext is shifted by a fixed number of positions down or up the alphabet. For example, with a shift of 3, A would be replaced by D, B by E, and so on. The cipher is named after Julius Caesar, who reportedly used it to communicate with his officials.

Basic Implementation of the Caesar Cipher

Below is a basic Python implementation of the Caesar Cipher that can both encrypt and decrypt text.

Example: Caesar Cipher in Python

def caesar_cipher(text, shift, mode='encrypt'):
    result = ""

    # Ensure the shift is within 0-25
    shift = shift % 26

    # Determine the direction of the shift
    if mode == 'decrypt':
        shift = -shift

    # Loop through each character in the text
    for char in text:
        # Check if the character is an uppercase letter
        if char.isupper():
            # Shift the character and wrap around using modulo 26
            result += chr((ord(char) + shift - 65) % 26 + 65)
        # Check if the character is a lowercase letter
        elif char.islower():
            # Shift the character and wrap around using modulo 26
            result += chr((ord(char) + shift - 97) % 26 + 97)
        else:
            # If it's not a letter, leave it unchanged
            result += char

    return result

# Example usage
plaintext = "Hello, World!"
shift = 3

# Encrypt the plaintext
encrypted_text = caesar_cipher(plaintext, shift, mode='encrypt')
print(f"Encrypted: {encrypted_text}")

# Decrypt the text
decrypted_text = caesar_cipher(encrypted_text, shift, mode='decrypt')
print(f"Decrypted: {decrypted_text}")
    

Explanation of the Code

  • Function Signature: The function caesar_cipher takes three parameters: text (the input string), shift (the number of positions to shift the characters), and mode (either “encrypt” or “decrypt”).
  • Shift Normalization: The shift is normalized using modulo 26 to ensure that it’s within the range of the alphabet.
  • Shift Direction: If the mode is “decrypt,” the shift is reversed by negating it.
  • Character Shifting: The function iterates through each character in the input text. If the character is a letter (either uppercase or lowercase), it is shifted by the specified amount. Non-letter characters (like spaces and punctuation) are left unchanged.
  • Output: The function returns the transformed string, either encrypted or decrypted based on the mode.

Example Output

For the provided example with a shift of 3:

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

Handling Edge Cases

The provided implementation correctly handles several edge cases:

  • Case Sensitivity: The cipher maintains the case of the letters (uppercase and lowercase).
  • Non-Alphabetic Characters: Non-alphabetic characters such as spaces, punctuation, and numbers are left unchanged.
  • Negative Shift Values: If a negative shift is provided, the code will automatically handle it by shifting the characters in the opposite direction.

Conclusion

The Caesar Cipher is a simple yet effective way to understand the basics of cryptography. This Python implementation demonstrates how to encrypt and decrypt text using the Caesar Cipher technique. While it’s not secure for modern encryption needs, it serves as a great educational tool for learning about substitution ciphers and programming in Python.