Caesar Cipher Implementation
Caesar Cipher Implementation
Introduction
The Caesar Cipher is one of the oldest and simplest encryption techniques, used by
Julius Caesar to protect sensitive military messages. It is a type of substitution cipher
where each letter in the plaintext is shifted by a certain number of positions down the
alphabet.
For example, with a shift of 3, 'A' becomes 'D', 'B' becomes 'E', and so on.
This document describes a Python program that implements the Caesar Cipher
algorithm for both encryption and decryption of text. The program allows users to
input a message and a shift value to encrypt or decrypt the message accordingly.
Program Overview
The Python program performs the following operations:
1. Accepts a message and a shift value from the user.
2. Encrypts the message using the Caesar Cipher.
3. Decrypts the message back to its original form using the same shift value.
Code Explanation
Encryption Function (encrypt)
The function takes the text and a shift value as input. It then iterates over each character
in the text:
If the character is uppercase or lowercase, it shifts it by the specified shift value.
Non-alphabetic characters are not encrypted and are added to the result as-is.
Decryption Function (decrypt)
This function simply calls the encrypt function with a negative shift value to reverse the
encryption process.
Code Implementation
# Function to encrypt text using Caesar Cipher
def encrypt(text, shift):
result = ""
# Loop through each character in the text
for char in text:
# Encrypt uppercase letters
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
# Encrypt lowercase letters
elif char.islower():
result += chr((ord(char) + shift - 97) % 26 + 97)
else:
# If the character is not a letter, add it as is
result += char
return result
Final thoughts
This program allows users to encrypt and decrypt messages using the Caesar Cipher,
demonstrating both the encryption and decryption processes with a simple shift. It
handles both uppercase and lowercase letters, leaving non-alphabetic characters
untouched. The program can be expanded by adding features such as handling different
alphabets or adding a graphical user interface (GUI).