Python | Caesar Cipher

By Casper_x | Python Programs | 6 Mar 2023


Caesar Cipher

 

Today we will see together how to create the Caesar cipher.

Let's start from the beginning..

It is essential to understand how the Caesar cipher works : each letter of the text is shifted by 'n' positions in the alphabet, where 'n' is the encryption key.

 

What is Caesar Cipher

 

The Caesar cipher is a relatively simple encryption technique that involves replacing each letter of the original message with another letter shifted by a certain number of positions in the alphabet. The number of shift positions is called the 'key' of the cipher.

The Caesar cipher is an example of a mono-alphabetic substitution cipher, which means that each letter of the original message is replaced with a unique letter in the encrypted message. 

This makes the Caesar cipher relatively easy to break, as the frequency of letters in the original message is preserved in the encrypted message. 

For example, if the key is ‘3’, the letter 'A' in the original message will shift by 3 to the left and will be replaced with the letter 'D' in the encrypted message, the letter 'B' will be replaced with the letter 'E', and so on.

To decrypt the message, one simply needs to shift each letter in the opposite direction, using the decryption key.

As a result, the Caesar cipher is not considered a secure encryption for sensitive communications, but it can be useful for teaching the basic principles of encryption and cryptography. More sophisticated variants of the Caesar cipher, such as poly-alphabetic substitution ciphers, can be used to enhance the security of the encryption.

Leave me a comment if you want a post about poly-alphabetic ciphers.

 

Program :

 

You must first define the various functions required for the program. In this case, you will need 6 functions

  • The encryption function
  • The decryption function
  • The save-to-file function
  • The decryption key verification function
  • ‘Another action’ function
  • ‘Main’ function

 

     1. Import module :

 

We will need to use the OS library to obtain the path to the backup directory.

 

import os

 

     2. ‘caesar_cipher’ function :

 

You will start by creating the ‘caesar_cipher( )' function that takes 2 arguments. : ‘text’ and ‘key’ (an integer from 1 to 25).

This function will allow encrypting the desired text using the Caesar cipher.

 

# Function to encrypt the text

def caesar_cipher(text, key):

 

Next, in the function, you will create an empty variable named 'cipher' to store the encrypted text.

 

    cipher = ""

 

The function use a loop to scan each character in the text, and checks if the character is a letter.

 

 # Scan each character in the text to be encrypted.

    for char in text:

        # Check if the character is a letter.

        if char.isalpha():

 

You must initiate a shift variable to 0 to see the correct letter offset.

 

            # Variable to store the letter offset.

            shift = 0

 

If it is a letter, it calculates the shift using the Caesar Cipher formula (uppercase & lowercase) and adds the final character to the encrypted text. 

 

            # Checks if the letter is a capital letter

            if char.isupper():

                # Calculation of the offset using the Caesar cipher formula (Uppercase)

                shift = ord(char) - ord('A') + key

                final_char = chr((shift % 26) + ord('A'))

            else:

                # Calculation of the offset using the Caesar cipher formula (lowercase)

                shift = ord(char) - ord('a') + key

                final_char = chr((shift % 26) + ord('a'))

                # Added the encrypted letter to the encrypted text.

            cipher += final_char

 

If it is not a letter, it adds the character as is to the encrypted text.

 

            else:

                # Added non-alphabetic characters to the encrypted text.

                cipher += char

Return ‘cipher’.

 

    # Returns the encrypted text.

    return cipher

 

Your ‘caesar_cipher( )’ function must look like this :

 

# Function to encrypt the text

def caesar_cipher(text, key):

    # Variable to store encrypted text

    cipher = ""

    # Scan each character in the text to be encrypted.

    for char in text:

        # Check if the character is a letter.

        if char.isalpha():

            # Variable to store the letter offset.

            shift = 0

            # Checks if the letter is a capital letter

            if char.isupper():

                # Calculation of the offset using the Caesar cipher formula (Uppercase)

                shift = ord(char) - ord('A') + key

                final_char = chr((shift % 26) + ord('A'))

            else:

                # Calculation of the offset using the Caesar cipher formula (lowercase)

                shift = ord(char) - ord('a') + key

                final_char = chr((shift % 26) + ord('a'))

                # Added the encrypted letter to the encrypted text.

            cipher += final_char

        else:

            # Added non-alphabetic characters to the encrypted text.

            cipher += char

    # Returns the encrypted text.

    return cipher

 

     3. ‘caesar_decipher’ function :

 

The function allows decrypting a text encrypted with the Caesar cipher from a file containing the encrypted text.

By encrypting text with the 'caesar_cipher' function, your encrypted text will be saved in the folder of your choice. You must copy the path to your 'file.txt' containing the encrypted text to use the 'caesar_decipher' function correctly.

 

The ‘caesar_decipher( )' function that takes 2 arguments. : ‘file_path’ and ‘key’

 

# Function to decrypt text from a file.

def caesar_decipher(file_path, key):

 

First, we need to open the file containing the encrypted text in read mode and store the contents of the file in a variable called 'cipher_text'.

 

    # Opening the file in read mode.

    with open(file_path, 'r') as file:

        cipher_text = file.read()

 

Initialize a variable named ‘deciphered_text' and assign it an empty value.

 

    # Variable to store decrypted text

    deciphered_text = ""

 

Then loops through each character in the text and performs the opposite shift calculation to decrypt it. If the character is not a letter, it adds the character as is to the decrypted text.

 

# Scan each character in the encrypted text.

    for char in cipher_text:

        if char.isalpha():

            shift = 0

            if char.isupper():

                shift = ord(char) - ord('A') - key

                final_char = chr((shift % 26) + ord('A'))

            else:

                shift = ord(char) - ord('a') - key

                final_char = chr((shift % 26) + ord('a'))

            deciphered_text += final_char

        else:

            deciphered_text += char

 

 

and prints the decrypted text to the console (optional).

 

  print("Decrypted text: ", deciphered_text)

 

Your ‘caesar_decipher( )’ function must look like this :

 

# Function to decrypt text from a file.

def caesar_decipher(file_path, key):

    # Opening the file in read mode.

    with open(file_path, 'r') as file:

        cipher_text = file.read()

    # Variable to store decrypted text

    deciphered_text = ""

    # Scan each character in the encrypted text.

    for char in cipher_text:

        if char.isalpha():

            shift = 0

            if char.isupper():

                shift = ord(char) - ord('A') - key

                final_char = chr((shift % 26) + ord('A'))

            else:

                shift = ord(char) - ord('a') - key

                final_char = chr((shift % 26) + ord('a'))

            deciphered_text += final_char

        else:

            deciphered_text += char

    print("Decrypted text: ", deciphered_text)

     4. ‘save_to_file( )’ function :

 

This function is somewhat similar to the one in the Password generator program without the option to save the text. The encrypted text will be automatically saved in the folder of your choice.

 

The first line defines the function and takes as input a variable 'cipher_text', which should contain the encrypted text that we want to save in a file.

 

# Function to save encrypted text in a file.

def save_to_file(cipher_text):

 

Next, the function asks the user to enter the name of the file in which the encrypted text should be saved, and then checks whether the '.txt' extension is already present in the entered file name. If it is not, the extension is added.

 

  # Asks the user to enter the file name

    file_name = input("Entrer le nom du fichier à enregistrer : ")

    # Added .txt extension to file name if not already present

    if not file_name.endswith('.txt'):

        file_name = file_name + '.txt'

 

You then need to define the file path where the encrypted text will be saved. (You need to change the folder path).

 

    directory = "/Your/Saving/Path/For/Encrypted/Text/"

 

The complete file path is then created using the ‘os.path.join()' function, which combines several path components to form a complete path.

Finally, the file is opened in 'write' mode (mode 'w' using the ‘open()' function), the cipher text is written to the file using the ‘write()' method of the file object, and the file is closed.

 

    file_path = os.path.join(directory, file_name)

    # Open the file in "write" mode and save the encrypted text.

    with open(file_path, "w") as file:

        file.write(cipher_text)

 

To finish, the function prints the complete file path where the encrypted text has been saved (optional).

 

print("Encrypted text saved as : ", file_path)

 

Your ‘save_to_file()’ function must look like this :

 

# Function to save encrypted text in a file.

def save_to_file(cipher_text):

    # Asks the user to enter the file name

    file_name = input("Entrer le nom du fichier à enregistrer : ")

    # Added .txt extension to file name if not already present

    if not file_name.endswith('.txt'):

        file_name = file_name + '.txt'

        # Set the path to save the file

    directory = "/Your/Saving/Path/For/Encrypted/Text/"

    file_path = os.path.join(directory, file_name)

    # Open the file in write mode and save the encrypted text.

    with open(file_path, "w") as file:

        file.write(cipher_text)

    print("Encrypted text saved as : ", file_path)

     5. ‘check_key’ function :

 

The 'check_key' function was used just to check if the encryption key you entered was correct. You can still enter the encryption key and decrypt the text using the 'caesar_decipher' function.

 

The ‘check_key' function requires 2 arguments to be defined (like 'caesar_decipher') : 'file_path', which should contain the file path to the file containing the encrypted text, and 'key', which should contain the encryption key used to encrypt the text.

We then open the file containing the encrypted text again in 'read' mode (mode 'r') and store the encrypted text in the variable 'cipher_text'.

 

# Function to check the encryption key.

def check_key(file_path, key):

    with open(file_path, 'r') as file:

        cipher_text = file.read()

Initialize a variable named ‘deciphered_text' and assign it an empty value.

 

    deciphered_text = ""

 

Next, the function iterates through each character of the encrypted text using a 'for' loop. If the current character is an alphabetical letter, the function calculates the offset between this character and the letter 'A' (for uppercase) or the letter 'a' (for lowercase), then subtracts the encryption key from this offset. 

The final character is then calculated using the resulting offset, bringing it back into the range of 26 letters using modulo (%), and adding the ASCII code of 'A' or 'a' to obtain the final character. If the current character is not an alphabetical letter, the final character is simply equal to the current character.

 

    for char in cipher_text:

        if char.isalpha():

            shift = 0

            if char.isupper():

                shift = ord(char) - ord('A') - key

                final_char = chr((shift % 26) + ord('A'))

            else:

                shift = ord(char) - ord('a') - key

                final_char = chr((shift % 26) + ord('a'))

            deciphered_text += final_char

        else:

            deciphered_text += char

 

Finally, when the loop is finished, the function returns the variable 'deciphered_text', which contains the deciphered text.

 

    return deciphered_text

 

Your ‘check_key( )’ function must look like this :

 

# Function to check the encryption key.

def check_key(file_path, key):

    with open(file_path, 'r') as file:

        cipher_text = file.read()

    deciphered_text = ""

    for char in cipher_text:

        if char.isalpha():

            shift = 0

            if char.isupper():

                shift = ord(char) - ord('A') - key

                final_char = chr((shift % 26) + ord('A'))

            else:

                shift = ord(char) - ord('a') - key

                final_char = chr((shift % 26) + ord('a'))

            deciphered_text += final_char

        else:

            deciphered_text += char

    return deciphered_text

     6. ‘another_action’ function :

 

This function has already been used in the Password Generator program so I won't go into detail as before. 

In summary, this function allows the user to choose whether or not to perform a new action and ensures that the user provides a valid response.

 

def another_action():

    choice = input("Do you want to perform another action ? (y/n) : ")

    if choice == 'y':

        main()

    elif choice == 'n':

        print("\nSee you soon !")

    else:

        print("Error : Invalid choice. Enter 'y' for yes or 'n' for no.")

 

     7. ’main’ function :

 

The ‘main()' function is the main function of the program. It handles the user's choice between encryption and decryption and performs the corresponding actions.

 

In the first part of the code, if the user enters 'e', they will be prompted to enter the text to be encrypted and the encryption key. The function ‘caesar_cipher()’ will be called to perform the encryption and the result will be saved to a file using the function ‘save_to_file()’. Then, the function ‘another_action()’ is called to ask the user if they want to perform another action.

 

def main():

    choice = input("Encrypt or decrypt ? (e/d) : ")

    if choice == 'e':

        text = input("Enter the text to be encrypted: ")

        key = int(input("Enter the encryption key (1-25) : "))

        cipher_text = caesar_cipher(text, key)

        save_to_file(cipher_text)

        another_action()

 

In the second part of the code, if the user enters 'd', they will be asked to enter the file path to decrypt and the decryption key. The ‘check_key()’ function will be called to verify if the decryption key is correct and decrypt the text accordingly. 

If the key is incorrect, an error message will be displayed. If the key is correct, the decrypted text will be displayed and the ‘another_action()’ function will be called to ask the user if they want to perform another action.

 

    elif choice == 'd':

        file_path = input("Enter the path to the file to be decrypted: ")

        key = int(input("Enter decryption key (integer) : "))

        deciphered_text = check_key(file_path, key)

        if deciphered_text != None:

            print("Decrypted text : ", deciphered_text)

            another_action()

        else:

            print(‘Error: The decryption key is incorrect.’)

            another_action()

Finally, we add a user input validation. If the user enters an invalid input, an error message will be displayed and the ‘another_action()’ function will be called to ask the user if they want to perform another action. 

 

    else:

        print(‘Error : Invalid choice. Enter 'c' for encrypt or 'd' for decrypt.")

        another_action()

 

Of course, it is necessary to call the 'main()' function at the end in order to run the program.

 

main()

 

That's the end of this post... It's been a lot of hard work for this publication, I hope it's detailed enough and that you enjoyed . 

As always, the complete code is at the end of the publication.

Thank you and congratulations to all those who didn't give up on reading this post.

Leave a comment if you have any questions

The next post will be the Scrabble Helper version with ‘tkinter’, which will be available in 1-2 days.

 

If you enjoy my blog posts, you can support me.

Thanks for you support 🫶

 

BTC : bc1qvfmetg2d36mmntrg56ld0tdrte8cqeygjxdpsg

ETH  | USDC | USDT : 0x02AbfBf22fA72d068Ff305e58dF782e58F863274

DOGE : DLtGbPrFvwW5y7jFuvuDAkZGNB2eAErAxA

 

See you soon ! 🤙

Casper_X 👻

 

     Want more programs ?

 

Take a look of these posts.

Scrabble Helper : https://www.publish0x.com/python-scrabble-helper/python-scrabble-helper-xvmqykg

QRcode generator : https://www.publish0x.com/python-scrabble-helper/python-qr-code-generator-xrgmxnx

Face detectionhttps://www.publish0x.com/python-scrabble-helper/python-face-detection-xjrwygy

Password generator : https://www.publish0x.com/python-scrabble-helper/python-password-generator-xyezmel

 

Here is the full program :

 

import os

# Function to encrypt the text
def caesar_cipher(text, key):
    cipher = ""
    for char in text:
        if char.isalpha():
            shift = 0
            if char.isupper():
                shift = ord(char) - ord('A') + key
                final_char = chr((shift % 26) + ord('A'))
            else:
                shift = ord(char) - ord('a') + key
                final_char = chr((shift % 26) + ord('a'))
            cipher += final_char
        else:
            cipher += char
    return cipher


# Function to decrypt text from a file.
def caesar_decipher(file_path, key):
    with open(file_path, 'r') as file:
        cipher_text = file.read()
    deciphered_text = ""
    for char in cipher_text:
        if char.isalpha():
            shift = 0
            if char.isupper():
                shift = ord(char) - ord('A') - key
                final_char = chr((shift % 26) + ord('A'))
            else:
                shift = ord(char) - ord('a') - key
                final_char = chr((shift % 26) + ord('a'))
            deciphered_text += final_char
        else:
            deciphered_text += char
    print("Decrypted text: ", deciphered_text)



# Function to save encrypted text in a file.
def save_to_file(cipher_text):
    file_name = input("Enter the name of the file to be saved : ")
    if not file_name.endswith('.txt'):
        file_name = file_name + '.txt'
    directory = "/Your/Saving/Path/For/Encrypted/Text/"
    file_path = os.path.join(directory, file_name)
    with open(file_path, "w") as file:
        file.write(cipher_text)
    print("Encrypted text saved as : ", file_path)


# Function to check the encryption key.
def check_key(file_path, key):
    with open(file_path, 'r') as file:
        cipher_text = file.read()
    deciphered_text = ""
    for char in cipher_text:
        if char.isalpha():
            shift = 0
            if char.isupper():
                shift = ord(char) - ord('A') - key
                final_char = chr((shift % 26) + ord('A'))
            else:
                shift = ord(char) - ord('a') - key
                final_char = chr((shift % 26) + ord('a'))
            deciphered_text += final_char
        else:
            deciphered_text += char
    return deciphered_text

def another_action():
    choice = input("Do you want to perform another action ? (y/n) : ")
    if choice == 'y':
        main()
    elif choice == 'n':
        print("\nSee you soon !")
    else:
        print("Error : Invalid choice. Enter 'y' for yes or 'n' for no.")

def main():
    choice = input("Encrypt or decrypt ? (e/d) : ")
    if choice == 'e':
        text = input("Enter the text to be encrypted: ")
        key = int(input("Enter the encryption key (1-25) : "))
        cipher_text = caesar_cipher(text, key)
        save_to_file(cipher_text)
        another_action()
    elif choice == 'd':
        file_path = input("Enter the path to the file to be decrypted: ")
        key = int(input("Enter decryption key (integer) : "))
        deciphered_text = check_key(file_path, key)
        if deciphered_text != None:
            print("Decrypted text : ", deciphered_text)
            another_action()
        else:
            print(‘Error: The decryption key is incorrect.’)
            another_action()
    else:
        print(‘Error : Invalid choice. Enter 'c' for encrypt or 'd' for decrypt.")
        another_action()

main()


How do you rate this article?

3


Casper_x
Casper_x

Python | Crypto | Javascript | Programming


Python Programs
Python Programs

Tutorials on the programming language 'Python'. In this blog you will find several basics Python programs to complete. Hope you enjoy the content !

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.