In this blog post, we will take a look at the world of secret messages by creating a Python program that encrypts and decrypts text using the substitution cipher method. This classic technique will allow you to scramble plain text into a coded message, and with the help of this program, you’ll be able to unscramble it back to its original form. This blog will walk you through the code step-by-step, making it easy to understand how Python can be used for simple encryption and decryption.
Overview:
- Design a substitution key to scramble messages.
- Transform plain text into an unreadable ciphertext using the key.
- Decipher the ciphertext back to its original form with the key.
First up, we will import the necessary modules:
import random
import string
In a Substitution Cipher we replace individual letters in a message with different letters or symbols. This creates a secret code that appears as random sequence to anyone who doesn’t know the key. To do so we will make a list of characters and symbols with string module, then scramble the same list with random module to make our key.
chars = list (string.punctuation + string.digits + string.ascii_letters + " ")
keys = list(chars.copy())
random.shuffle(keys)
Now the main part, Encryption !!
We run a for loop to map the plain text letter to the cipher text letter according to it’s index number. By the end of this covert operation, our for loop will have replaced every letter in our message, creating a completely new, scrambled message – the ciphertext!
#Encryption
plain_text = input("Enter a message to encrypt: ")
cipher_text = " "
for letter in plain_text:
index = chars.index(letter)
cipher_text += keys[index]
print("Original Message : ",plain_text)
print("Encrypted Message: ",cipher_text)
Reverse the Shuffle !!
Using the key again, our loop will go through each letter in the ciphertext. For each letter, it will consult the key and swap it back to its original form from the plaintext message.
#Decryption
cipher_text = input("Enter a message to decrypt: ")
plain_text = " "
for letter in cipher_text:
index = keys.index(letter)
plain_text += chars[index]
print("Original Message : ",cipher_text)
print("Decrypted Message: ",plain_text)

And just like that, our secret message program is complete! You can now encrypt messages and crack the codes to reveal hidden messages.
Thank you for reading !!