Python
Python

 

Introduction

The Caesar cipher is one of the simplest and most widely known encryption techniques. It is named after Julius Caesar, who used this cipher to protect his messages. The basic idea behind this cipher is to shift each letter of the plaintext by a fixed number of positions down or up the alphabet.

In this program, we will demonstrate how to implement both encryption and decryption using the Caesar cipher. The user can specify a key (shift value), and the program will encrypt or decrypt the message accordingly.

Objective

The objective of this program is to demonstrate how the Caesar cipher works, and provide a simple way to encrypt and decrypt messages. The program will:

  • Implement the Caesar cipher for encryption and decryption.
  • Allow users to input a plaintext message and a key for the cipher.
  • Encrypt the message and provide the output ciphertext.
  • Decrypt the ciphertext back into the original message using the same key.

Python Code for Caesar Cipher


# Caesar Cipher Implementation in Python

def encrypt(plaintext, key):
    """Encrypt the plaintext using Caesar cipher with the given key (shift)."""
    ciphertext = ""
    for char in plaintext:
        if char.isalpha():
            shift = key % 26
            start = 65 if char.isupper() else 97
            ciphertext += chr((ord(char) - start + shift) % 26 + start)
        else:
            ciphertext += char  # Non-alphabetic characters remain unchanged
    return ciphertext

def decrypt(ciphertext, key):
    """Decrypt the ciphertext using Caesar cipher with the given key (shift)."""
    plaintext = ""
    for char in ciphertext:
        if char.isalpha():
            shift = key % 26
            start = 65 if char.isupper() else 97
            plaintext += chr((ord(char) - start - shift) % 26 + start)
        else:
            plaintext += char  # Non-alphabetic characters remain unchanged
    return plaintext

# Main program to interact with the user
def main():
    print("Welcome to the Caesar Cipher Program!")
    
    # Input the message and the key
    message = input("Enter your message: ")
    key = int(input("Enter the shift key (an integer): "))
    
    # Encrypt the message
    encrypted_message = encrypt(message, key)
    print(f"Encrypted message: {encrypted_message}")
    
    # Decrypt the message back
    decrypted_message = decrypt(encrypted_message, key)
    print(f"Decrypted message: {decrypted_message}")

# Run the program
if __name__ == "__main__":
    main()

Explanation of the Program Structure

The program consists of three main components: the encryption function, the decryption function, and the main function that interacts with the user. Here’s how each part works:

  • Encrypt function: This function takes two arguments: the plaintext message and the shift key. It loops through each character of the plaintext, checks if it’s an alphabetic character, and shifts it by the specified key. Non-alphabetic characters (e.g., spaces, punctuation) are not altered.
  • Decrypt function: This function works similarly to the encrypt function but shifts the characters in the opposite direction to restore the original message.
  • Main function: This is the entry point of the program. It prompts the user for a message and a shift key, calls the encrypt and decrypt functions, and displays the results on the screen.

To run this program, you simply need to provide a plaintext message and a shift key. The program will output both the encrypted message and the decrypted message.

How to Run the Program

To run this program, follow these steps:

  • Ensure that you have Python installed on your machine.
  • Copy the Python code above into a new file named caesar_cipher.py.
  • Open a terminal or command prompt and navigate to the directory where the file is saved.
  • Run the program using the following command:
    python caesar_cipher.py
  • Enter the message and the shift key when prompted. The program will display the encrypted message and the decrypted message.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)