IBM Z Security - Group home

Caesar Cipher implementation in Python

  
In this technical article, we are going to take a look at how we can implement the Caesar Cipher using Python Programming Language. We will take a look at the key generation, encryption and decryption algorithms individually.

Python Image
If you want to learn about Caesar Cipher, you can refer to my technical article titled "Know about the Caesar Cipher, one of the earliest known and simplest ciphers!!!" at https://community.ibm.com/community/user/ibmz-and-linuxone/blogs/subhasish-sarkar1/2020/07/04/caesar-cipher

Key Generation Algorithm
As the name suggests, the key generation algorithm generates the Caesar Cipher key. Our code should check that the key is greater than 0 and less than 26.

#Key Generation
key = int(input("Please enter the Caesar Cipher key that you would like to use. Please enter a number between 1 and 25 (both inclusive)."))

while key < 1 or key > 25:
  print("  Unfortunately, you have entered an invalid key. Please enter a number between 1 and 25 (both inclusive) only.")
  key = int(input())

print("  Thanks for selecting the Caesar Cipher key. The Key selected by you is " + str(key))
Please enter the Caesar Cipher key that you would like to use. Please enter a number between 1 and 25 (both inclusive).0
  Unfortunately, you have entered an invalid key. Please enter a number between 1 and 25 (both inclusive) only.
-11
  Unfortunately, you have entered an invalid key. Please enter a number between 1 and 25 (both inclusive) only.
26
  Unfortunately, you have entered an invalid key. Please enter a number between 1 and 25 (both inclusive) only.
3
  Thanks for selecting the Caesar Cipher key. The Key selected by you is 3

Encryption Algorithm

The Caesar cipher works by encrypting messages through the substitution of each letter in the message plaintext with a letter which is a fixed amount (the key) away in the alphabet and it wraps around, if necessary.

 

Our code should implement the following algorithm steps for each and every character constituting the message plaintext.

1. Check whether a letter
2. If not a letter, add the same to the ciphertext without changing it
3. If a letter, check whether a capital or lowercase letter
4. Maintain the letter casing, move the letter up the alphabet (using the Caesar Cipher key), thereby substituting the letter
5. In case the movement makes it past the end of the alphabet, wrap around to the beginning
6. Add the new letter to the ciphertext

 

You can check the following website "https://cryptii.com/pipes/caesar-cipher" to play around with Caesar Cipher.

 

In order to achieve the task of moving the letter up the alphabet (using the Caesar Cipher key), each letter will be represented as a number, to which will be added the Caesar Cipher key in order to get the cipher letter. We will use two standard Python functions, namely, ord() and chr(), in order to accomplish this. The ord() function takes a letter as an argument and returns the corresponding integer ASCII code. The chr() function does the exact opposite of taking in an integer ASCII code as its argument and returning the letter that the integer ASCII code represents.

 

By default, Python uses the ASCII encoding scheme. You can refer to the website "https://www.rapidtables.com/code/text/ascii-table.html" as an easy reference. When a wrap around happens, we would have to make sure that we correctly start back at ‘A’ or ‘a’, depending on whether we are dealing with a capital or lowercase letter.

 

#The plain text message
#Allow the user to enter the plaintext message through the console
plain_text = str(input("Please enter the plain text message that you would like the Caesar Cipher Encryption Algorithm to encrypt for you."))
cipher_text = ""
print("  Thanks for entering the plain text message. You have entered the following plain text message.")
print("       " + plain_text)

#The Caesar Cipher Encryption algorithm
for letter in plain_text:
    if letter.isalpha():
        val = ord(letter)
        val = val + key
        if letter.isupper():
            if val > ord('Z'):
                val -= 26
            elif val < ord('A'):
                val += 26
        elif letter.islower():
            if val > ord('z'):
                val -= 26
            elif val < ord('a'):
                val += 26
        new_letter = chr(val)
        cipher_text += new_letter
    else:
        cipher_text += letter

print("  Cipher Text -----> " + cipher_text)
Please enter the plain text message that you would like the Caesar Cipher Encryption Algorithm to encrypt for you.I am a proud Mainframer.
  Thanks for entering the plain text message. You have entered the following plain text message.
       I am a proud Mainframer.
  Cipher Text -----> L dp d surxg Pdlqiudphu.

Decryption Algorithm

The decryption algorithm simply decrypts a cipher text message back to the original plain text message. The decryption algorithm does that by simply reversing the process that had been previously employed by the encryption algorithm - while the encryption algorithm had moved up the alphabet, the decryption algorithm moves the letters down the alphabet instead. In the encryption algorithm, the positive Caesar Cipher key was added to the ASCII representation of each and every letter comprising the plain text message. In the decryption algorithm, the Caesar Cipher key will be a negative number because we to move the letter in the opposite direction. Otherwise, we have almost the same algorithm for both the encryption as well as decryption processes.

#The Caesar Cipher Decryption algorithm
key1 = key
key1 = -key1
plain_text = ""
print("  Cipher Text -----> " + cipher_text)

for letter in cipher_text:
    if letter.isalpha():
        val = ord(letter)
        val = val + key1
        if letter.isupper():
            if val > ord('Z'):
                val -= 26
            elif val < ord('A'):
                val += 26
        elif letter.islower():
            if val > ord('z'):
                val -= 26
            elif val < ord('a'):
                val += 26
        new_letter = chr(val)
        plain_text += new_letter
    else:
        plain_text += letter

print("  Plain Text -----> " + plain_text)
  Cipher Text -----> L dp d surxg Pdlqiudphu.
  Plain Text -----> I am a proud Mainframer.



***********************************************************************************************************************************************************
The author of the technical article, Subhasish Sarkar (SS), is an IBM Z Champion for 2020.
***********************************************************************************************************************************************************