Encrypt and Decrypt with Terminal
Modifying the set key to and set letter to blocks to encrypt and re-flashing a project to get a ciphertext character isn’t very efficient. It would be much easier for your project to pass a function, a key, and a word to a function and let it encrypt or decrypt the whole string. Getting there can be broken into three steps:
- Get it to work with user-entered characters in a loop
- Add a loop to make it perform the cipher on all characters in a word
- Move the working code from the main loop into a function
Another reason for setting it up this way is that you can replace a Caesar cipher function with a different encryption function, and the main project might only need one block modified to get it to work.
Caesar Cipher on Terminal-Entered Characters
In this example, the terminal will prompt you for a key and a letter, and then display the Caesar cipher result. Previously, the encryption key was hard-coded as 5. With this project, you can enter 5, or 13 for ROT-13, or any other value you decide to use. Next, enter the letter to encrypt, and the project displays the ciphertext result in the terminal.
Example project: caesar_terminal_letters
- Enter caesar_terminal_letters, then flash it into the micro:bit.
- Make sure your keyboard is set to CAPS LOCK.
- Open the terminal make sure that local echo is on and follow the prompts. Valid keys are from -25 to 25.
- Try encrypting a character, and then decrypting with the negative value of the key you encrypted with.
Example: Encrypt A with 13, then decrypt N with -13 to get back to A.
How caesar_terminal_letters Works
Instead of hard-coding set key to (5) and set letter to (“M”), like in caesar_cipher_letter, this project makes it work during runtime with:
Before doing the Caesar cipher, it uses set letter to (upper(letter)) which changes any lower-case letter to upper-case. …just in case you forgot to set your keyboard’s CAPS LOCK.
Did You Know?
These steps from the previous example sketch can be performed in one block:
Here’s how it would look:
This more compact format will be used in the next example project.