Substitution Cipher Implementation - File Encryption/Decryption



Task

Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.

This type of Encryption/Decryption scheme is often called a Substitution Cipher.



Related tasks

 Caesar cipher
 Rot-13
 Vigenère Cipher/Cryptanalysis


See also

 Wikipedia: Substitution cipher


 
from string import printable
import random
 
EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random()))
 
def encode(plaintext, key):
    return ''.join(key[printable.index(char)] for char in plaintext)
 
def decode(plaintext, key):
    return ''.join(printable[key.index(char)] for char in plaintext)
 
original = "A simple example."
encoded = encode(original, EXAMPLE_KEY)
decoded = decode(encoded, EXAMPLE_KEY)
print("""The original is: {}
Encoding it with the key: {}
Gives: {}
Decoding it by the same key gives: {}""".format(
    original, EXAMPLE_KEY, encoded, decoded))