Caesar Cipher: create your own secret messages

Cryptography is the process of converting ordinary plain text into an incomprehensible text (secret code) and vice-versa. The algorithm that is used to transform a plain text into a secret code (and vice-versa) is called Cipher.


Julius Caesar, a celebrated Roman general, politician and scholar, used to correspond with his men via cryptic messages. Only he and his men knew the key to decode the messages. This ensured that his enemies won’t be able to understand the messages if by any chance they get their hands on it.



The method used by Julius Caesar to conceal his messages is called Caesar Cipher. It is one of the earliest and simplest method of encoding. In this cipher, each letter (or ‘symbol’ in terms of cryptography) is shifted according to a key in a cyclic manner. The key is any number from 1 to 26, as there are 26 alphabets in English language. So, with a key equal to 2, A becomes C, B becomes D, Z becomes B and so on.


An example of Caesar cipher with key equal to 3 is:

Plain_text: FROG PRINCE

Encrypted_text: IURJ SULQFH


We now have a basic idea of Caesar Cipher. We can see that we only need a string and a key to perform encryption in python.


We will write a program that asks the user to provide a file containing the plain text and the key and then encrypts the plain text and stores the result in another file.


Before moving forward, there are some prerequisites that should be known, which are as follows:

  • To represent each letter as a number called an ordinal (so that we can modify each letter to get a new letter by performing mathematical operations) we use ASCII codes. ASCII stands for American Standard Code for Information Interchange; it connects each character to a number between 32 and 126. ( Modern computers use UTF-8 instead of ASCII. But UTF-8 is backwards compatible with ASCII, so the UTF-8 ordinals for ASCII characters are the same as ASCII’s ordinals. )

  • The capital letters ‘A’ to ‘Z’ has ASCII value 65 to 90.

  • The lowercase letters ‘a’ to ‘z’ has ASCII value 97 to 122.

  • The numeric digits ‘0’ to ‘9’ has ASCII value 48 to 57.

  • The function ord() is used to get the ASCII value of the character.

>> ord('A')
65
>> ord('p')
112
>> ord(' ')
32
>> ord('2')
50
  • The function chr() is used to get the character from the corresponding ordinal value.

>>chr(73)
'I'
>>chr(55)
'7'
>>chr(33)
'!'

ENCRYPTION


Let us define an algorithm to write the program code:

  • Ask the user for the name of the file containing the plaint ext and convert the text of the file into a string.

  • Ask the user for the value of key.

  • Create an empty string to store the result.

  • Identify each character in the string.

  • Convert each character to its corresponding ASCII value using the function ord().

  • If the character is a space or comma or full stop, add it to the empty string.

  • If the character is numeric, add the key to ord(character) and find how many position away it is from 48 (i.e. ‘A’) and then add it to 48. This ensures that the conversion remains cyclic.

  • If the character is uppercase, add the key to ord(character) and find how many position away it is from 65 (i.e. ‘A’) and then add it to 65. This ensures that the conversion remains cyclic.

  • If the character is not upper case, add the key to ord (character) and find how many position away it is from 97 (i.e. ‘a’) and then add it to 97. This ensures that the conversion remains cyclic.

  • Convert the ordinal back to a letter character using the function char ().

  • Add the character to the empty string to store the cryptic text.

  • Repeat until the end of string.

  • Store the result into a file called encrypted_text.txt.

The program code is given below:

def encrypt(): 
    
    inp=input('Enter the name of the file :')
    key=int(input('Enter the key :'))
    handle=open('{}.txt'.format(inp),'r')
    lines=handle.readlines()
    for line in lines:
        line=line.strip()
    handle.close()
    
    
    cipher = ''
    for char in line: 
        if char == ' ' or char =='.' or char ==',':
            cipher = cipher + char
        elif char.isnumeric():
            cipher = cipher + chr((ord(char) + key - 48) % 10 + 48)
        elif  char.isupper():
            cipher = cipher + chr((ord(char) + key - 65) % 26 + 65)
        else:
            cipher = cipher + chr((ord(char) + key - 97) % 26 + 97)
                
    handle_out=open("encrypted_text.txt",'w')
    handle_out.write(cipher)
    handle_out.close()
    print('\nPlain text is:   '+line)
    print('Cryptic text is: '+cipher)
    
    return cipher

The output of the above code is:

>>encrypt()
Enter the name of the file :plain_text Enter the key :2  Plain text is:   Give me a red pen of any colour. Cryptic text is: Ikxg og c tgf rgp qh cpa eqnqwt. 
Out[2]:
'Ikxg og c tgf rgp qh cpa eqnqwt.'



DECRYPTION


Similarly, we can write the function for decryption which asks the user for the name of the file containing cryptic text and the key and then decrypts the text.


The program code for decryption is as follows.

def decipher():
    # Enter encypted_text as the file name.
    inp=input('Enter the name of the encrypted file.')
    key=int(input('Enter the key'))
    handle=open('{}.txt'.format(inp),'r')
    lines=handle.readlines()
    for line in lines:
        line=line.strip()
    handle.close()
    
    
    decipher = ''
    for char in line: 
        if char == ' ' or char =='.' or char ==',' or char =='\''or char ==':' or char == '!':
            decipher = decipher + char
        elif char.isnumeric():
            decipher = decipher + chr((ord(char) - key - 48) % 10 +48)
        elif  char.isupper():
            decipher = decipher + chr((ord(char) - key - 65) % 26 +65)
        else:
            decipher = decipher + chr((ord(char) - key - 97) % 26 +97)
    
    print('\nEncrypted text is: '+line)
    print('Decrypted text is: '+decipher)
    
    return decipher

The output of the above code is:

>>decipher()
Enter the name of the encrypted file.encrypted_text Enter the key2  Encrypted text is: Ikxg og c tgf rgp qh cpa eqnqwt. Decrypted text is: Give me a red pen of any colour. 
Out[63]:
'Give me a red pen of any colour.'

We can also achieve decryption by using encrypt () function, for that we provide the name of the file containing the encrypted text and the negative value of the key. Here is the example.

>> encrypt()
Enter the name of the file :encrypted_text Enter the key :-2  Encrypted text is: Ikxg og c tgf rgp qh cpa eqnqwt. Decrypted text is: Give me a red pen of any colour. 
Out[66]:
'Give me a red pen of any colour.'

Have fun creating your own secret messages!



Contact Us

Tel: (+91) 0120  4118730  

Time :   10 : 00  AM -  08 : 00 PM IST 

Registered address: G-69, Sector 63, 

 Noida - 201301, India

We Provide Services Across The different countries

USA    Australia   Canada   UK    UAE    Singapore   New Zealand    Malasia   India   Ireland   Germany

CodersArts is a Product by Sofstack Technology Solutions Pvt. Ltd.

  • CodersArts | Linkedin
  • Instagram