# Arup Guha # Substitution Cipher Encrypter # Precondition: message is all lowercase letters, key is 26 letters long # and a permutation of 'a' - 'z', so also all lowercase. # Postcondition: returns the encryption of message with key (substitution) def encrypt(message,key): # Store result here. res = "" # Go through each character. for i in range(len(message)): # Subtract ascii values and use that as the index into key. res = res + (key[ord(message[i])-ord('a')]) return res # Returns the inverse function stored in key. def makedecryptkey(key): # List of 26 characters. newkey = [' ']*26 # Do the inverse mapping. for i in range(len(key)): temp = ord(key[i])-ord('a') newkey[temp] = chr(i+ord('a')) # There must be a better way to do this! res = "" for i in range(len(newkey)): res = res + newkey[i] return res # My hard-coded test case. myKey = "qwertyuiopasdfghjklzxcvbnm" plain = "thequickbrownfoxjumpsoverthelazydog" # Encrypt and print ciphertext. cipher = encrypt(plain, myKey) print("The ciphertext is",cipher) # Make the decryption key and show it for testing purposes. decryptKey = makedecryptkey(myKey) print("Key to decrypt is", decryptKey) # We can reuse the encrypt function here! plainBack = encrypt(cipher, decryptKey) print("The decrypted message is", plainBack)