#!/usr/bin/python3 # -*- coding: utf-8 -*- # Simple Substitution Cipher # https://www.nostarch.com/crackingcodes (BSD Licensed) import sys, random LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: myMessage = "If a man is offered a fact which goes against his inst\ incts, he will scrutinize it closely, and unless the evidence is overwh\ elming, he will refuse to believe it. If, on the other hand, he is offe\ red something which affords a reason for acting in accordance to his in\ stincts, he will accept it even on the slightest evidence. The origin o\ f myths is explained in this way. -Bertrand Russell" myKey = "LFWOAYUISVKMNXPBDCRJTQEGHZ" myMode = "encrypt" # Set to either 'encrypt' or 'decrypt'. if not keyIsValid(myKey): sys.exit("There is an error in the key or symbol set.") if myMode == "encrypt": translated = encryptMessage(myKey, myMessage) elif myMode == "decrypt": translated = decryptMessage(myKey, myMessage) print("Using key %s" % (myKey)) print("The %sed message is:" % (myMode)) print(translated) def keyIsValid(key: str) -> bool: keyList = list(key) lettersList = list(LETTERS) keyList.sort() lettersList.sort() return keyList == lettersList def encryptMessage(key: str, message: str) -> str: return translateMessage(key, message, "encrypt") def decryptMessage(key: str, message: str) -> str: return translateMessage(key, message, "decrypt") def translateMessage(key: str, message: str, mode: str) -> str: translated = "" charsA = LETTERS charsB = key if mode == "decrypt": # For decrypting, we can use the same code as encrypting. We # just need to swap where the key and LETTERS strings are used. charsA, charsB = charsB, charsA # Loop through each symbol in message: for symbol in message: if symbol.upper() in charsA: # Encrypt/decrypt the symbol: symIndex = charsA.find(symbol.upper()) if symbol.isupper(): translated += charsB[symIndex].upper() else: translated += charsB[symIndex].lower() else: # Symbol is not in LETTERS; just add it translated += symbol return translated def getRandomKey() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key) if __name__ == "__main__": main()