Now that the scripts are sending different case letters, spaces and punctuation, it’s time to choose a different cipher. Reason being the caesar() function cannot accommodate those extra characters without modifications, but the ascii_shift() function can. It was introduced in the Cybersecurity: Encryption Intro tutorials’ ASCII Shift Cipher activity.
After the import statements, the ascii_shift() function is added. With def ascii_shift(key, text), it accepts key and text parameters and returns the encrypted result. Most importantly, the text can contain any printable ASCII character.
from microbit import * import radio ''' Function converts plaintext to ciphertext using key ''' def ascii_shift(key, text): result = "" for letter in text: ascii = ( ord(letter) + key - 32 ) % 94 + 32 result = result + chr(ascii) return result
After the ascii_shift() function, the script starts with the usual radio.on, radio.config, and sleep calls along with a couple print statements to help you identify which micro:bit is running which version of the script.
''' Script starts from here... ''' radio.on() radio.config(channel=7) sleep(1000) print("micro:bit transceiver A") print()
Before the main loop, the script prompts you for an encryption key. So long as both transceivers are using the same key, the messages sent will be faithfully reproduced by the receiver and vice-versa.
text = input("Enter key: ") key = int(text)
These are messages similar to the original unencrypted radio texting app. Without them, an empty terminal might be confusing, so the prompts are intended to encourage users to start typing messages.
print() print("Type messages, press enter to send.") print("Received messages will also be displayed.") print()
Inside the main loop, the script checks if you have typed any characters in the terminal. If you have, an input statement captures what you typed. Before transmitting it with radio.send, it does the extra step of tx = ascii_shift(key, tx) to encrypt the string you typed.
while True: if uart.any(): tx = input("Send: ") tx = ascii_shift(key, tx) radio.send(tx)
The main loop also checks for messages from the radio. When one is received, it is stored in the message variable. At this point, message is ciphertext, which has to be decrypted. That’s what message = ascii_shift(-key, message) does, returning the plaintext message. …and after print("Receive: ", message), you’ll be able to see and read it in the terminal.
message = radio.receive() if message: message = ascii_shift(-key, message) print("Receive: ", message)