Substitution Cipher in Python

In this article, we will talk about ciphers, to be more specific substitution cipher in Python. Mainly in cryptography, the ciphertext is used to encrypt the plain text. According to a fixed system, the “units” may be single letters, triplets of letters, pairs of letters, mixtures of the above, etc.

Assume Romeo wants to send a letter to Juliet, and he doesn’t want to write the letter such a way that anyone can read it. So to encrypt the letter, he shifts every single alphabet by 5 units. That means becomes f, b becomes and so on.
So if Romeo wants to send a message: “Meet me this evening”; he will just write: “RJJY RJ YMNX JAJSNSL”

Now by any mistake, someone else sees that letter, he will not understand the exact meaning of the letter. And at the end of the day, when Juliet gets the letter, she will just shift 5 units back to every alphabet and read the letter. So here the shift 5 is the secret key to this letter. And if some middle person gets to know about this method between two lovers, he may try to make all possible shifts to get the exact meaning of this letter.  So he shifts 1 letter at a time and understands the words are not making any sense. And then shifts 2 letters, then 3 letters and so on. But when he shifts 5 letters, he will get the exact meaning of the letter. So we can conclude that it can be easily breakable by any middle man. This is known as Caesar Cipher. Since it is not safe, we no longer use this method.

Now we will learn more safest way to use the above method. What if we change the alphabets with some random symbols, and then shifts the letter by certain units? Then if the middle man knows about the shifting unit number, still he will not able to get the exact letters.

Substitution Cipher in Python

English Speaks Out A Loud”: English a statistical language, which means English is easily vulnerable. Even though we changed the letters or shifts the letters, still it is easily breakable. The most common word in English is “E”  Hence, if one can find out the position of E, can easily decode the message.

Since this article is all about cryptography and breaking or decrypting the cryptography, let’s jump into Python to make our own Ceaser Cipher.

In cryptography, we play with letters, hence we need string module in Python. So,

import string

Let’s first see how to change or shift the alphabet by a certain unit. Assume the message is “Hello World”. We can use the replace method from the string module to replace the letter with another letter.

a = "Hello world"
a.replace("H", "J")
'Jello world'

Now since we know the method to replace letters,  let’s see all the alphabets in English

print(string.ascii_letters)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Now assume we have a message in which the cipher will be performed.
“Hi, I am Diptam Paul, a content writer at CodeSpeedy.com
I hope I can make easily readable articles so that you can understand everything.”

So now let’s write a code, where every alphabet will substitute by 5 letters.

import string
dict = {}
for i in range(len(string.ascii_letters)):
    dict[string.ascii_letters[i]] = string.ascii_letters[i - 5]    #You can substitute with any letters e.g. -1, / +1 / -2 etc
    
#Now if you wanna see the substituted letters, just print dict
print(dict)
{'a': 'V', 'b': 'W', 'c': 'X', 'd': 'Y', 'e': 'Z', 'f': 'a', 'g': 'b', 'h': 'c', 'i': 'd', 'j': 'e', 'k': 'f', 'l': 'g', 'm': 'h', 'n': 'i', 'o': 'j', 'p': 'k', 'q': 'l', 'r': 'm', 's': 'n', 't': 'o', 'u': 'p', 'v': 'q', 'w': 'r', 'x': 's', 'y': 't', 'z': 'u', 'A': 'v', 'B': 'w', 'C': 'x', 'D': 'y', 'E': 'z', 'F': 'A', 'G': 'B', 'H': 'C', 'I': 'D', 'J': 'E', 'K': 'F', 'L': 'G', 'M': 'H', 'N': 'I', 'O': 'J', 'P': 'K', 'Q': 'L', 'R': 'M', 'S': 'N', 'T': 'O', 'U': 'P', 'V': 'Q', 'W': 'R', 'X': 'S', 'Y': 'T', 'Z': 'U'}

Now we will use this dict, to convert our input files.

data = ""  #Empty String

#Now we need to make a new file where the converted texts will save
file = open("Output_text.txt", "w")



#Now we have to read the text file
with open("example.txt") as f:
    while True:
        #Now we need the file character by character
        c = f.read(1)   #When we read a file send a boolean value there
        if not c:
            print("End of file")
            break
        if c in dict:
            data = dict[c]
        else:
            data = c
        file.write(data)  #Writing the converted texts into Output_text.txt
file.close()

Now if you open the Output_text.txt, you will see the converted texts.
“Cd, D Vh ydkoVh KVpg, V XjioZio rmdoZm Vo xjYZNkZZYt.Xjh
D cjkZ D XVi hVfZ ZVndgt mZVYVWgZ VmodXgZn, nj ocVo tjp XVi piYZmnoViY ZqZmtocdib.”

Also read: Implementing Rail-fence Cipher in Python

Leave a Reply

Your email address will not be published. Required fields are marked *