Learn About Caesar Cipher in Python

Cryptography is the study of the science behind securely transmitting a message from a sender to a receiver. The goal is to prevent a third party from accessing a message. It is achieved by converting the original message into a form that can only be interpreted if one has access to the key. Thus, the key is known only to the sender and the receiver. There are several algorithms in cryptography, but today, we will be looking into caesar cipher in python.

Introduction to Caesar cipher Algorithm

Caesar cipher is one of the oldest and the most commonly known cryptography technique. It is a weak encryption technique for practical implementation but for learning the basics of cryptography. Therefore, it is the best one to get started with. It is based on substitution cipher. Each character is shifted by a specific number of characters, which is the key. Before we dive further into this algorithm, we will understand some basic cryptography terms.

Terms in cryptography

Plaintext: It is the original message which is sent by the sender to the receiver.

Ciphertext: It is obtained when an encryption algorithm has been applied on the plaintext. Basically, it is the scrambled form of the plaintext which cannot be interpreted without the key.

Encryption: It is the technique behind conversion of a plaintext to its ciphertext.

Decryption: It is the technique behind the conversion of the ciphertext to its original plaintext.

Key: It is the value that, when fed to the encryption and decryption algorithm, gives ciphertext and plaintext, respectively.

How does Caesar Cipher work in Python?

The working of the caesar cipher is dependent on the key selected. Each alphabet in the plaintext will be shifted by an amount equal to the value of the key.

For example, if our plaintext is: ‘ABCD’ and the key is 1, then each letter will be replaced by the letter shifted by 1. So, A will be replaced by B, B will be replaced by C, C will be replaced by D, and D will be replaced by E. Thus, the ciphertext obtained would be ‘BCDE.’

caesar cipher python

Had the key size been 3, the ciphertext of the plaintext ‘ABCD’ would be ‘DEFG’.

Caesar Cipher Formula

The formula to convert a given plaintext ‘P’ to ciphertext ‘C’ using key ‘K’ is:

C = ( P + K ) % 26

Similarly, the formula to convert a given ciphertext ‘C’ to plaintext ‘P’ using key ‘K’ is:

P = ( C - K ) % 26

Here, we assign each alphabet a number – A = 0, B = 1, C = 2, D = 3,…,Z = 25. We perform a summation between the number concerning the alphabet and the key value. Then, we perform a modulus operation on that value. For the obtained value, we assign it the alphabet, which is the ciphertext alphabet.

caesar cipher python

Suppose our plaintext was ‘ATTACK’ and the key was 10, then for each letter, the encryption would be:

A : C1 = ( 0 + 10 ) % 26 = 10 % 26 = 10 = K
T : C2 = ( 19 + 10 ) % 26 = 29 % 26 = 3 = D
T : C3 = ( 19 + 10 ) % 26 = 29 % 26 = 3 = D
A : C4 = ( 0 + 10 ) % 26 = 10 % 26 = 10 = K
C : C5 = ( 2 + 10 ) % 26 = 12 % 26 = M
K : C6 = ( 10 + 10 ) % 26 = 20 % 26 = U

Therefore, the obtained ciphertext is : ‘KDDKMU’

Caesar Cipher Using Python

Now, we will be writing the code for implementing the caesar cipher algorithm. We shall be defining two functions – one for encryption and another for decryption. Lets us look at both separately.

Encryption algorithm explaination

To perform encryption, we will be creating a user defined function –

caesar_encryption(): The function will accept two arguments – plaintext and the key-and print the encrypted ciphertext. We shall take the plaintext and the key as the input from the user and pass them into the function.

Inside the function, we have a string named encryption_str of zero length. We have taken a for loop for iterating the plaintext. Inside the for loop, we have taken three if-else conditions. The first one is for handling uppercase letters, the second one for lowercase letters, and the last else case is for handling non-alphabet characters. For checking uppercase and lowercase, we have used isupper(), and islower() functions.

Then we have used the ord() function to obtain the Unicode code point representation of the letter. The uppercase alphabets start from the Unicode value 65 with A = 65, B = 66, etc. Similarly, the lowercase alphabets start from 97 with a = 97, b = 98, etc. We have subtracted 65 and 97 for uppercase and lowercase characters respectively to reduce each alphabet to the A = 0, B = 1, C = 2,…,Z = 25 representation. And then, we have applied the ‘C = ( P + K ) % 26’ formula and added 65 for lowercase and 97 for uppercase for that value to get the Unicode integer value for the obtained ciphertext letter.

Then, we have to use the chr() function, which is used to obtain the alphabet from its Unicode integer value. We have simply concatenated that character with the encryption_str string. If the character is not an alphabet, we would simply concatenate it as it is with the encryption_str string.

def caesar_encryption(plaintext,key):
  encryption_str = ''
  for i in plaintext:
    if i.isupper():
      temp = 65 + ((ord(i) - 65 + key) % 26) 
      encryption_str = encryption_str + chr(temp)                              
    elif i.islower():
      temp = 97 + ((ord(i) - 97 + key) % 26)
      encryption_str = encryption_str + chr(temp)
    else:
      encryption_str = encryption_str + i  

  print("The ciphertext is:",encryption_str)

plaintext = input("Enter the plaintext:")
key = int(input("Enter the key:"))
caesar_encryption(plaintext,key)

The output for the above encryption algorithm is:

Enter the plaintext:attack on the palace!
Enter the key:10
The ciphertext is: kddkmu yx dro zkvkmo!

Decryption algorithm explaination

We are using the same method for performing decryption. We have a user-defined function name caesar_decryption() which takes the ciphertext and the key as the arguments and prints the plaintext. It takes the ciphertext and key as input from the users.

We have a zero-length string named decryption_str, with which we will be concatenating our plaintext. Apart from the formula, the only slight difference here is that for both uppercase and lowercase if statements, we will be checking if the ( C – K ) value is negative or not from the ‘P = ( C – K ) % 26’ formula. If it is negative, then we will add 26 to it before performing modulus. If not, then we will refrain from doing that. Just like the encryption algorithm, the no alphabet characters will be unchanged.

def caesar_decryption(ciphertext,key):
  decryption_str = ''
  for i in ciphertext:
    if i.isupper():
      if ((ord(i) - 65 - key) < 0):
        temp = 65 + ((ord(i) - 65 - key + 26) % 26) 
      else:
        temp = 65 + ((ord(i) - 65 - key) % 26) 
      decryption_str = decryption_str + chr(temp)                              
    elif i.islower():
      if ((ord(i) - 97 - key) < 0):
        temp = 97 + ((ord(i) - 97 - key + 26) % 26) 
      else:
        temp = 97 + ((ord(i) - 97 - key) % 26) 
      decryption_str = decryption_str + chr(temp)
    else:
      decryption_str = decryption_str + i  

  print("The plaintext is:",decryption_str)

ciphertext = input("Enter the ciphertext:")
key = int(input("Enter the key:"))
caesar_decryption(ciphertext,key)

We will be taking the same ciphertext from the encryption algorithm example to check the plaintext. The output will be:

Enter the ciphertext:kddkmu yx dro zkvkmo!
Enter the key:10
The plaintext is: attack on the palace!

FAQ’s

What is the limitation of caesar cipher algorithm?

The limitation of the caesar cipher is that it is prone to brute force attack, meaning that by trying every key combination, the plaintext can be obtained. This is because there are only 26 unique keys possible.


That wraps up caesar cipher with python. Do let us know your views in the comments below.

Till then, Keep Learning!

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
DTP
DTP
2 years ago

Thank you for this comprehensive and understandable walk-through.