def indexForLetter(letter): """Takes as input a character. For any of the 26 uppercase or lowercase English letters, returns its index 0, 1, 2, ..., or 25 in the alphabet. For any other character, returns None.""" if letter >= 'A' and letter <= 'Z': return ord(letter) - ord('A') elif letter >= 'a' and letter <= 'z': return ord(letter) - ord('a') else: return None def letterForIndex(index): """Takes as input an integer. If it's between 0 and 25, then returns the corresponding uppercase English letter. Otherwise, returns None.""" if index >= 0 and index <= 25: return chr(index + ord('A')) else: return None def encryptSubstitution(s, subst): """Takes in a string (of English letters and perhaps other characters) and a list of substitutions for the substitution cipher. Returns the string with all of the English letters encrypted.""" c = "" for i in range(len(s)): index = indexForLetter(s[i]) if index == None: # The current character is not a letter; just glom it on. c += s[i] else: # The current character is a letter; encrypt it. c += subst[index] return c def decryptSubstitution(c, subst): """Takes in a string (of English letters and perhaps other characters) and a list of substitutions for the substitution cipher. Returns the string with all of the English letters decrypted.""" # Build the inverse substitution list. invSubst = [] for i in range(26): # Compute the letter corresponding to this i. letter = letterForIndex(i) # Find the index of that letter in the original substitution list. index = subst.index(letter) # Convert that index back to a letter; this is the ith substitution. invSubst.append(letterForIndex(index)) # Decryption is just encryption with the inverse substitution. return encryptSubstitution(c, invSubst) # If the user directly ran this file (rather than imported it), then run this # demonstration. if __name__ == "__main__": print "The substitution is:" substitution = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'] print substitution print "The plaintext is:" message = "WHEN I WAS A YOUNG BOY OF ABOUT EIGHT YEARS OF AGE MY FAMILY GOT A NEW PUPPY HER NAME WAS ABBY SHE WAS HALF GOLDEN RETRIEVER AND HALF SOMETHING ELSE UNKNOWN BUT PERHAPS LABRADOR RETRIEVER IT IS SAFE TO SAY THAT ABBYS MOTHERS PREGNANCY WAS UNEXPECTED AND UNWANTED BY HER OWNERS ON THE WAY HOME FROM THEIR HOUSE THE ADORABLE ABBY ABRUPTLY VOMITED IN MY LAP" print message print "The ciphertext is:" ciphertext = encryptSubstitution(message, substitution) print ciphertext print "After decryption, the recovered message is:" print decryptSubstitution(ciphertext, substitution)