Another encryption example is the substitution cipher. With a substitution cipher, each character in an alphabet maps to a cryptabet with different characters in the same position. The simplest example of this is the Atbash or reverse-alphabet cipher.
Alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cryptabet: ZYXWVUTSRQPONMLKJIHGFEDCBA
# substitution_cipher_atbash from microbit import * # Atbash cipher. def atbash(text): alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" crypta = "ZYXWVUTSRQPONMLKJIHGFEDCBA" result = "" for letter in text: letter = letter.upper() index = alpha.find(letter) result = result + crypta[index] return result # The script starts executing statements from here. sleep(1000) print("Set your keyboard to CAPS LOCK.") print() while True: plaintext = input("Enter a CAPS LOCK string: ") result = atbash(plaintext) print("result =", result)
Your code has to use result = atbash(plaintext) to get the ciphertext—no key required.
The atbash function has one parameter, text. The built-in key is the cryptabet, a reverse alphabet in this case. Like the other cipher functions, this one also declares an empty string named result to store the result.
def atbash(text):
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
crypta = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
result = ""
Inside the loop that generates the ciphertext, it starts the same way, by finding the index of the letter in the alphabet with index = alpha.find(letter). What’s different is ciphertext = ciphertext + crypta[index]. This grabs the character with the same index in the cryptabet, and adds it to the result.
for letter in text: letter = letter.upper() index = alpha.find(letter) result = result + crypta[index] return result
Example: Let’s say that letter is E. It’s index in the alphabet is 4. The character at crypta[4] is V, so V would be added to the result string.
Here is an alphabet that also includes digits, a space and some characters that would be useful for making a dictionary.
Alphabet: abcdefghijklmnopqrstuvwxyz 123456789:,{}'
Your Cryptabet: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _