Decryption of Simple Substitution Cipher



In this chapter, you can learn about simple implementation of substitution cipher which displays the encrypted and decrypted message as per the logic used in simple substitution cipher technique. This can be considered as an alternative approach of coding.

Example - Decryption Using Simple Substitution Cipher

You can use the following code to perform decryption using simple substitution cipher −

main.py

import random

chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \
   'abcdefghijklmnopqrstuvwxyz' + \
   '0123456789' + \
   ':.;,?!@#$%&()+=-*/_ []{}`~^"\'\\'

def generate_key():
   """Generate a key for our cipher"""
   shuffled = sorted(chars, key=lambda k: random.random())
   return dict(zip(chars, shuffled))

def encrypt(key, plaintext):
   """Encrypt the string and return the ciphertext"""
   return ''.join(key[l] for l in plaintext)

def decrypt(key, ciphertext):
   """Decrypt the string and return the plaintext"""
   flipped = {v: k for k, v in key.items()}
   return ''.join(flipped[l] for l in ciphertext)

def show_result(plaintext):
   """Generate a resulting cipher with elements shown"""
   key = generate_key()
   encrypted = encrypt(key, plaintext)
   decrypted = decrypt(key, encrypted)
   
   print('Key: ',key)
   print('Plaintext: ',plaintext)
   print('Encrypted: ',encrypted)
   print('Decrypted: ', decrypted)

show_result('Hello World. This is demo of substitution cipher')

Output

The above code gives you the output as shown here −

(myenv) D:\Projects\python\myenv>py main.py
Key:  {'A': 'Z', 'B': 'o', 'C': '#', 'D': 'r', 'E': 'V', 'F': 'W', 'G': 'K', 'H': '%', 'I': '&', 'J': 'H', 'K': 'f', 'L': 'b', 'M': '[', 'N': '8', 'O': 'F', 'P': 'O', 'Q': '/', 'R': 'a', 'S': 'c', 'T': 'J', 'U': '9', 'V': '{', 'W': 'B', 'X': 'P', 'Y': '=', 'Z': '.', 'a': 'u', 'b': "'", 'c': 's', 'd': 'q', 'e': 'y', 'f': ',', 'g': '^', 'h': '~', 'i': '2', 'j': ';', 'k': 'C', 'l': 'I', 'm': 'A', 'n': '}', 'o': '-', 'p': 'Q', 'q': '"', 'r': 'S', 's': 'n', 't': ':', 'u': 'U', 'v': '+', 'w': 'd', 'x': 'D', 'y': 'Y', 'z': '7', '0': '*', '1': ']', '2': 'k', '3': 'R', '4': ')', '5': '3', '6': 'z', '7': 'E', '8': 'X', '9': 't', ':': '1', '.': 'x', ';': '\\', ',': '@', '?': 'v', '!': 'L', '@': ' ', '#': '5', '$': '6', '%': '!', '&': ';', '(': '?', ')': '4', '+': '0', '=': 'l', '-': 'T', '*': 'M', '/': 'N', '_': 'p', ' ': 'a', '[': 'j', ']': 'w', '{': 'h', '}': 'e', '`': 'g', '~': '_', '^': 'm', '"': '(', "'": 'm', '\\': 'G'}
Plaintext:  Hello World. This is demo of substitution cipher
Encrypted:  %yII-aB-SIqxaJ~2na2naqyA-a-,anU'n:2:U:2-}as2Q~yS
Decrypted:  Hello World. This is demo of substitution cipher

(myenv) D:\Projects\python\myenv>
Advertisements