Your Turn: Add Encryption

Did You Know: Again, Stronger Together

As mentioned earlier, devices on a network need both encryption AND protection from malformed packets.  This does not normally take many lines of code.  Like the earlier example, both Sender and Receiver scripts need the encrypt/decrypt function (ascii_shift in our example).  

def ascii_shift(key, text):
    result = ''
    for letter in text:
        ascii = ( ord(letter) + key - 32 ) % 94 + 32
        result = result + chr(ascii)
    return result

The Sender script also needs to encrypt the packet before sending:

        packet = ascii_shift(17, packet)

…and the Receiver needs to decrypt the packet after receiving:

        packet = ascii_shift(-17, packet)

 

In Python for computers (as opposed to MicroPython for the micro:bit), an encryption/decryption module would be imported.  Instead of adding a comparatively weak encryption function, you’d import a module like PyCryptodome, Cryptography, or PyNaCl and use its stronger cryptography methods to encrypt and decrypt.

Your Turn: Add Encryption

The last task in hardening the keyboard-controlled cyber:bot is to implement both encryption and exception handling.

  • Modify the sender and receiver scripts using the comments tagged (Your Turn) in the images below as a guide.
  • Name and save your modified sender and receiver scripts.
  • Repeat the tests yet again, this time to verify that the application still works and is still immune to malformed packets.
  • Examine the transmitter and receiver micro:bit serial monitors, and verify that the encryption and decryption are happening as planned.

 

Sender Script Modifications

 

Receiver Script Modifications