Encrypt a Single Letter
This next project will encrypt individual letters with the Caesar cipher. As written it encrypts the letter M with a key of 5.
Example project: caesar_encrypt_letter
- Enter and flash caesar_encrypt_letter into the micro:bit.
- Make sure your keyboard is set to CAPS LOCK.
- Open the terminal and verify that:
- The plaintext letter is M and its index is 12
- The new index is 17 with the resulting ciphertext letter R.
Decrypt with Caesar Cipher
What if a project receives a Caesar encrypted character and a key? Do you need to make another project? The answer is no. To decrypt a ciphertext letter to plaintext, just use the negative of the key that encrypted it. So, if a ciphertext character was encrypted with 5, it can be decrypted with -5.
Remember how a plaintext letter M encrypted to a ciphertext letter R when the key was 5? To decrypt a ciphertext letter of R with a key of 5, just run it through the same Caesar cipher with a key of -5. The result will be the plaintext character M.
- If you don’t already have it open, reopen caesar_encrypt_letter.
- Set the key to -5 and the plaintext letter to “R”.
- Flash the modified project into the micro:bit.
- Verify that the ciphertext letter (which is really the plaintext letter) result is “M”.
Mess around with some different letters. Do they all work perfectly? Did you run into any errors? If you used any letter above “F” you probably noticed that the new index is negative and the result doesn’t exist. That’s because we can’t search for something using negative values. It’s a pretty simple fix that we can make.
- Start by adding an if (index < 0) before you start searching for the result.
- Add 26 to the index if it is below 0 which should loop it properly