How Using the Random Key Works

How It Works: radio_send_images_caesar_key_unknown

This section only explains modifications that make it use a random key and send strings at a slower rate.  For info on the program before modifications, check Share Something Personal - Encrypted.

Adding import random makes the random methods available so that the script can use random.randint().

Adding key = random.randint(1, 25) sets the key equal to a randomly generated integer in the 1 through 25 range.  This statement was placed above the while True: loop so that it gets executed before the main loop starts sending repeated encrypted messages.  That way, the script sets the key value once, and then uses it with every repetition of the while True: loop.  

Each time you restart the micro:bit, there is a 1 in 25 chance you will get the same key.  Conversely, there is a 24 out of 25 chance that the key will be different.

In the main loop, changing packet = caesar(3, packet) to packet = caesar(key, packet) makes it so that the main loop repeatedly uses the one key value that was randomly determined before the main loop started repeating.

The sleep(2500) was changed to sleep(6000).  Intentionally slowing down the broadcast rate gives the online editor enough time to take a 0.2 s break between each line printed.  This will reduce the WebUSB tendency to make printing errors.

How It Works: radio_receive_images_caesar_brute_force

The brute force receiver removed the statements that assumed key was 3 and displayed it.

        # packet = caesar(-3, packet)             # <- comment
        # print("packet:", packet)                # <- comment
        # display.show(getattr(Image, packet))    # <- comment

In place of those three statements, it uses a loop that decrypts and prints the decrypted packet’s result to the terminal with each of the 25 possible keys.  The for key in range(-1, -26, -1)  loop repeats the indented-below statements with key set to -1, then -2, -3, and so on up through -25.  Each time through the loop, result = caesar(key, packet) decrypts the packet for that repetition’s key value.  Then, print("key:", key, "result:", result) displays the key and decrypted string for each iteration of the loop.  

        for key in range(-1, -26, -1):            # <- add
            result = caesar(key, packet)          # <- add
            print("key:", key, "result:", result) # <- add
            sleep(200)                            # <- add
        print()                                   # <- add

Lastly, sleep(200) delays before repeating the loop to give the online editor’s WebUSB connection extra time to transfer information to the terminal (since it seems to need it at the time of this writing).  After all 25 loop repetitions, print() displays an empty line before the while True: loop repeats and another 25 keys and decrypted strings are displayed.