Here is python code for the substitution cipher.
# A key, which could be randomly generated using
# >>> x = list("abcdefghijklmnopqrstuvwxyz")
# >>> random.shuffle(x)
# >>> print x
key = "rbtvpjlwyaigusxzcdmnofhekq"
# The message to encrypt
plaintext = "Hide the gold in the tree stump."
# Replace spaces by x and switch to lower case
plaintext = plaintext.replace(" ", "x").lower()
alphabet = "abcdefghijklmnopqrstuvwxyz"
ciphertext = ""
for char in plaintext:
# the variable char is one of the letters in the plaintext
# First, check if char is an alphabet character
if char in alphabet:
# Lookup the index of char within alphabet. This turns "a"
# into 0, "b" into 1, "c" into 2, and so on, since the index
# location of the letter in the alphabet string is its number.
i = alphabet.index(char)
# Now access the cooresponding index of key. So if for
# example char was "c", i becomes 2 so we use key[2] which
# happens to be "t".
ciphertext += key[i]
else:
# the character is not an alphabet character like the period, just add it directly.
ciphertext += char
print(ciphertext)
Implement code for decryption of the substitution cipher. You should be able to mostly copy the encryption code with a few modifications. Try it out to make sure it encrypts and decrypts the messages properly.