DEV Community 👩‍💻👨‍💻

Cover image for Caesar Cipher Encryption Decryption Using Python
Ramakrushna Mohapatra
Ramakrushna Mohapatra

Posted on

Caesar Cipher Encryption Decryption Using Python

What is Caesar Cipher Cryptography

A Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence

Encryption

For instance, here is a Caesar cipher using a left rotation of three places, equivalent to a right shift of 23 (the shift parameter is used as the key):

Plain A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Cipher X Y Z A B C D E F G H I J K L M N O P Q R S T U V W
When encrypting, a person looks up each letter of the message in the "plain" line and writes down the corresponding letter in the "cipher" line.

Plaintext: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD

In simple word

plain text = "hello"
shift = 5
cipher text = "mjqqt"
print output: "The encoded text is mjqqt"
Enter fullscreen mode Exit fullscreen mode

Code For Encrypton

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

def encrypt(plain_text,shift_amount):
    cipher_text =""
    for letter in plain_text:    
        position = alphabet.index(letter)
        new_position = position +shift_amount
        if new_position > 25:
            new_position2 = new_position-26
            new_letter2 = alphabet[new_position2]
            cipher_text += new_letter2
        else:
            new_letter1 = alphabet[new_position]
            cipher_text += new_letter1
    print(f"The encoded text is {cipher_text}.")

encrypt(plain_text = text,shift_amount = shift)
Enter fullscreen mode Exit fullscreen mode

The condition checked for new_position > 25 because there is no alphabet after 25 [List starts from 0 so total element will be 25]. To get back to starting position once it crosses last element we have to check this condition.

Decryption

In simple word

cipher text = "mjqqt"
shift = 5
plain text = "hello"
print output: "The encoded text is hello"
Enter fullscreen mode Exit fullscreen mode

Code For Decrypton

def decrypt(cipher_text, shift_amount):

  plain_text = ""
  for letter in cipher_text:
    position = alphabet.index(letter)
    new_position = position - shift_amount
    plain_text += alphabet[new_position]
  print(f"The decoded text is {plain_text}")
Enter fullscreen mode Exit fullscreen mode

for decrypt we don't need to subtract or add anything. As we know in a list from right-end side if we want to do slicing or indexing, its start count from -1.
So, if cipher first element = a
shift number = 5
plain text = 1-5 = -4
alphabet[-4] = w
so, here we don't need to adjust anything. It will work fine directly. Just remember the local variable and the function calling should be nearly same as mentioned in the encryption part.

These above two code part is to give you over view about how caesar-cipher works. We can optimize the code with adding some ne constraints like:

  • Adding a logo.
  • What if the user enters a shift that is greater than the number of letters in the alphabet?
  • What happens if the user enters a number/symbol/space?
  • Can you figure out a way to ask the user if they want to restart the cipher program?

I am adding the final code here with solution of all the query mentioned above. Its also optimized version of the Encryption and Decryption code mention above.

Final Code

logo = """           
 ,adPPYba, ,adPPYYba,  ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba,  
a8"     "" ""     `Y8 a8P_____88 I8[    "" ""     `Y8 88P'   "Y8  
8b         ,adPPPPP88 8PP"""""""  `"Y8ba,  ,adPPPPP88 88          
"8a,   ,aa 88,    ,88 "8b,   ,aa aa    ]8I 88,    ,88 88          
 `"Ybbd8"' `"8bbdP"Y8  `"Ybbd8"' `"YbbdP"' `"8bbdP"Y8 88   
            88             88                                 
           ""             88                                 
                          88                                 
 ,adPPYba, 88 8b,dPPYba,  88,dPPYba,   ,adPPYba, 8b,dPPYba,  
a8"     "" 88 88P'    "8a 88P'    "8a a8P_____88 88P'   "Y8  
8b         88 88       d8 88       88 8PP""""""" 88          
"8a,   ,aa 88 88b,   ,a8" 88       88 "8b,   ,aa 88          
 `"Ybbd8"' 88 88`YbbdP"'  88       88  `"Ybbd8"' 88          
              88                                             
              88           
"""
print(logo)

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
    shift_amount *= -1
  for char in start_text:

    if char in alphabet:
      position = alphabet.index(char)
      new_position = position + shift_amount
      end_text += alphabet[new_position]
    else:
      end_text += char
  print(f"Here's the {cipher_direction}d result: {end_text}")


should_end = False
while not should_end:

  direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
  text = input("Type your message:\n").lower()
  shift = int(input("Type the shift number:\n"))

  shift = shift % 26

  caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

  restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n")
  if restart == "no":
    should_end = True
    print("Goodbye")
Enter fullscreen mode Exit fullscreen mode

In one program we are doing both encryption and decryption by asking the user. Please go through this and give it a like and comment what you think about the program and description provided.

If you want to see the details of my Python Bootcamp Programs and resources. Please go this below Github link and explore.

If you want to create any type ASCII word, Please go through the below link. I have generated that logo from this site.

ASCII Art Generator

Gihub Link for This program

Oldest comments (0)

🌚 Life is too short to browse without dark mode