LEARN.PARALLAX.COM
Published on LEARN.PARALLAX.COM (https://learn.parallax.com)
Home > Cybersecurity: Encryption Intro

Cybersecurity: Encryption Intro

What it’s about

Encryption is the process of encoding information into an alternate form that is unintelligible. Decryption is the process of decoding that alternate form to get the original information. 

Encryption is used to protect private information as it is transmitted through channels that can be monitored, like radio communication and the Internet. Most websites, apps, and servers communicate over secure channels, meaning that they encrypt the data before sending and decrypt after receiving.

In this tutorial, you will start with some basic encryption concepts using one of the oldest and most simple forms of encryption, the Caesar cipher. Above is a picture of the Caesar cipher with a key of 5 applied to the first two characters in “HELLO”. The encrypted version of the H E in HELLO is M J. Can you complete the last three characters in the ciphertext?

This tutorial will guide you through making Makecode projects that can encrypt and decrypt with the Caesar cipher and some other simple ciphers. 

Before you start

You will need:

  • A micro:bit module (on or off a cyber:bot)
  • A USB A to MicroB cable
  • A computer with:
    • Access to the makecode.microbit.org editor
  • Note that Google Chrome Labs Serial Terminal is used in this tutorial’s screen captures.

Complete these tutorials first:

  • Making micro:bit programs
  • Computer – micro:bit Talk
  • (Optional) Strings & Characters Primer
  • (Optional) Dictionary Primer

After you finish

You will be able to make projects that use simple ciphers to encrypt and decrypt characters, words, and even complete messages. You will also have gained familiarity with keys, ciphers, and other basic cryptography terms. Along the way, you will apply some of the string manipulation skills introduced in the Strings Primer.

Encrypt Letters by Hand

The shift cipher is a simple form of encryption that has been used since at least the days of the Roman Empire. Julius Caesar’s encrypted letters are the first widely known use of a shift cipher. A shift cipher is a type of substitution cipher that replaces each letter in a message with an adjacent letter from the alphabet one, two, three, or ten or more letters away.

If you answered that the ciphertext from the previous page is MJQQT, you are correct! See how the key of 5 is applied? Starting with H at the beginning of the plaintext, count 5 letters to the right in the alphabet and use that character (M) in the ciphertext version. 

What about decryption? If the key is 5 and your ciphertext is MJQQT, count 5 letters earlier in the alphabet for each letter. For example, the plaintext H in HELLO is 5 letters to the left of the ciphertext letter M from MJQQT.

What happens with a key of 5 when you get to a letter like X? No problem, just start over at A…but make sure to count the jump from Z to A as a letter. For example, if the plaintext letter is X, then the five-character shift is Y Z A B C, and the ciphertext letter is C. In other words, when you run out of characters, restart at the beginning. This is called a circular shift.

Now that you can see how to encrypt characters with the Caesar cipher, let’s try it! 

  • Pick a number in the 1 to 25 range (smaller will take less time). This number is your “key”.
  • Pick a simple word, like your first name, or maybe your pet’s name.
  • Encrypt each letter in the word like this:
    • Start with the first letter – your first plaintext letter.
    • Find it in the alphabet.
    • Count to the right by key letters and pick that letter as your ciphertext letter. 
  • Example: If your key is 3 and your letter is G, counting over 3 will make your ciphertext letter J.
  • Remember, after Z, your next counted letter will be A.
  • Repeat the process for each letter in the word.

Next, show a friend how to decrypt it: 

  • Start with the first ciphertext letter.
  • Find it in the alphabet.
  • Count key letters to the left to find the plaintext letter. Keep in mind, if you reach A, your next counted letter will be Z.
  • Repeat the process for every letter in the word to rebuild the plaintext word.

Encrypt Letters with a Caesar Cipher Project

Alright, are you ready to make a project that does what you just did by hand? 

Before getting started, think about this set of steps as a conversion between by-hand to pseudo code for programming.

  1. Store the key in a variable
  2. Store the plaintext letter you are starting within a variable
  3. Create an alphabet
  4. Find the index of that plaintext letter in the alphabet
  5. Add the key to the index
  6. Find and store the ciphertext letter at the new index

Now let’s go!

Find a Character

A project that does the Caesar cipher has to start by finding a character in an alphabet. In this example, you will make a project that creates an alphabet string and finds the index of a certain character. In other words, it will tell you that A has an index of 0, B has an index of 1, and so on, up through Z, which has an index of 25.

Example project: find_letter_in_alphabet

  • Enter find_letter_in_alphabet.
  • Flash it into the micro:bit.

When the project runs, the terminal should print index = 12 since that is the index of M in the string alpha.

  • Make sure your keyboard is set to CAPS LOCK.
  • Open the terminal and verify that it displays:

    letter = M, index = 12
  • Change set letter to (“M”) to set letter to (“D”).
  • Flash the modified project.
  • Verify that the terminal displays:
    letter = D, index = 3
  • Repeat this process for “A”, “B”, “Y”, and “Z”.

How find_letter_in_alphabet Works

Every cipher begins with an alphabet, so the project starts by creating a string named alpha, which contains all the uppercase letters in the alphabet. 

The () find index of () method is something available to each string in Makecode. () find index of () searches the string for whatever text is passed to it from inside the second parentheses, and it returns the index where the text is first located. Remember that the index numbers in a string start at zero. So, the first character A has an index of 0, B has an index of 1, and so on, through Z with an index of 25. In this counting system, M has an index of 12 in the alpha string. So, set letter to (“M”) followed by (alpha) find index of (letter) returns 12.


“…and now, for something completely different!” 

You might have already experimented with the () find index of () method in Try This: Find the Substring. It had examples of finding the starting index values of words like “Arthur” and “run”, and even used the index to decide what to do next. In this encryption example, the alpha string’s () find index of () method is instead used to locate a single letter within a string.

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

How Caesar Letter Encryption Works

Once your project knows the index of a character in a string, it can simply add the key to the index and use the result to get the ciphertext character. 

The first four statements are the same as the previous activity. So when set key to (5) and the plaintext set letter to (“M”), (alpha) find index of (letter) returns 12, which gets stored in index. Now for the Caesar shift. change index by (key) evaluates to index = 12 + 5, which is 17. With set result to (char from (alpha) at (index)), that’s set result to (char from (alpha) at (17)). Since char from (alpha) at (17) returns “R”, that’s the ciphertext character the result variable stores.

Circular Shift and the Modulus (Division Remainder) Calculation

Remember the circular shift? That’s when the next character after Z in a Caesar shift wraps around to A. For example, with a plaintext letter of X and a key of 5, we want a ciphertext letter of C. 

This circular shift is made possible by set index to (remainder of (index) / (26)). The typical symbol for this is a % operator, which is called the modulus operator, and it returns what’s left over from an integer division operation. Unlike floating point division where 19 / 5 = 3.8, integer division’s quotient result would be 3 with a remainder of 4. Integer division always rounds down, so 19 // 5 = 3. The remainder is 19 % 5 = 4. That remainder of 4 is another way of expressing the 0.8 part of 3.8 because 0.8 * 5 = 4. Another way to think about the remainder is that 3 * 5 = 15, which is 4 below the original numerator of 19.

After change index by (key), 24 is still Y, and 25 is still Z, but 26 isn’t in the alphabet. In fact, char from alpha at 26 would cause an exception in the project by making it look for a character that’s not there. 26 needs to be changed to 0, 27 needs to be changed to 1, 28 needs to be changed to 2 and so on… That’s exactly what set index to (remainder of (index) / (26)) does, as you can see from the right column in this table. It also works fine for values below 26.

Integer quotient, integer remainder
  24 // 26 = 0       24 % 26 = 24
  25 // 26 = 0       25 % 26 = 25
  26 // 26 = 1       26 % 26 = 0
  27 // 26 = 1       27 % 26 = 1
  28 // 26 = 1       28 % 26 = 2
  29 // 26 = 1       29 % 26 = 3

Here is an example with a key of 5 and the plaintext letter X. See how the result of 28 % 26 is 2? The letter C in the alpha string has an index of 2, and that’s the correct result if the project starts with X and a key of 5.

Decrypt with the Same Cipher

Let’s say your project receives the ciphertext letter R and an encryption key of 5. How would it decrypt to get back to the plaintext letter M? 

The answer is to use the same algorithm, but reverse the sign of the key so that it’s -5. The index of R is 17, so change index by (key) would be index = 17 + -5 = 12. That’s the index of M, and that’s how the project can use the negative value of a key to decrypt from a ciphertext character back to the original plaintext character.

Your Turn – ROT-13

The ROT-13 cipher is a special case of the Caesar cipher where the characters are shifted right 13 places. Are you ready to create a ROT-13 cipher? Hint: set key to (13)!

  • Set up a ROT-13 cipher, and test with each letter in H E L L O. If you did it correctly, the ciphertext result should be U R Y Y B.

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:

  1. Get it to work with user-entered characters in a loop
  2. Add a loop to make it perform the cipher on all characters in a word
  3. 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.

Apply Caesar Cipher to Words from Terminal

This project places the Caesar cipher in a loop. This will allow you to type entire words for encrypting/decrypting! It still also works with single characters if that’s all you want to encrypt. 

Example project: caesar_terminal_words

  • Enter caesar_terminal_words, then flash it into the micro:bit.

  • Open the terminal, make sure local echo is checked, and follow the prompts. Valid keys are from -25 to 25.
  • Try encrypting HELLO with the key set to 5.
  • Try decrypting MJQQT with the key set to -5.
  • Write a short message for your friend or lab partner and give them the key to decrypt it.

How caesar_terminal_words Works

Inside the forever loop, the project stores a number you enter into an int variable named key. Then, it stores a word you type in a string variable named word.

In addition to the alpha (alphabet) string, a second empty string named result is created to store the result.

After that, a for… loop goes through each letter in the plaintext string. After making sure the letter is upper-case, it applies the Caesar cipher with a few blocks. The first finds the index of the new character with set index to (remainder of ((alpha) find index of (letter) + key ) / 26). After that, there’s an if… loop that makes sure it isn’t a negative index. The last block adds the character to whatever is already in the ciphertext string with set result to (join (result) (char from (alpha) at (index))).

Before repeating the loop, the ciphertext is printed to the terminal.

Caesar Cipher in a Function

Why move the Caesar cipher routine to a function? One advantage would be that you can swap it out with other, better encryption functions, or even function/method calls to a module. As an example, in the next activity, you will replace the caesar function with another one called ascii_shift. After the function swap, your project will only need one block changed!

Example project: caesar_cipher_function

  • Enter caesar_cipher_function, then flash it into the micro:bit.

The functionality is identical to the previous example (caesar_terminal_words).

  • Open the terminal, check that local echo is checked, follow the prompts, and verify that the functionality matches the previous project.
  • Take a look at the actual project you have to work with, it’s the parts inside both the start here block and the forever loop. 

See how all that project has to do is use call caesar to encrypt the word?

How It Works

Your project now gets the ciphertext from this one block:

The caesar function has two parameters, key and word. Keep in mind that word could also be ciphertext that you are converting back with a negative key value. Inside the function, it does all the same steps as caesar_terminal_words, and then returns the result.

ASCII and Other Simple Ciphers

The simple ciphers we examine in this tutorial are called monoalphabetic substitution ciphers, where one character always maps to some other letter in the adjusted alphabet. 

In addition to the Caesar cipher, you will see names like Atbash, Affine, Beaufort, Hill, and others. Here, you can experiment with Atbash, mixed alphabet, and a very useful variation on the Caesar shift cipher that uses ASCII characters. 

ASCII Shift Cipher

The Caesar cipher works well as an introduction to ciphers, but it’s not overly practical. With only 25 keys and every word separated by a space, it’s definitely one of the easiest ciphers to crack. The Caesar cipher is also not a very good fit for encrypting radio data since CAPS LOCK letters with no other characters or spaces would make a project to send an encrypted version of this dictionary really difficult:

{‘start’ : 3, ‘after’ : ‘Liftoff! ‘}

The ASCII Shift Cipher works on all printable characters, including spaces, so that dictionary string would be no problem to encrypt and decrypt with ASCII Shift. Although it’s still considered very weak in the encryption world, 93 different keys is still more secure than 25.

Example project: ascii_shift_cipher

  • Enter ascii_shift_cipher, then flash it into the micro:bit.

  • Open the terminal, make sure local echo is checked, and follow the prompts. Valid keys are from -93 to 93.
  • Try encrypting Cases, spaces, and punctuation! with the key set to 5.
  • Try decrypting Hfxjx1%xufhjx1%uzshyzfynts& with the key set to -5.
  • Try encrypting and decrypting a string like: {‘start’ : 3, ‘after’ : ‘Liftoff! ‘}

How It Works: ascii_shift_cipher

Assuming you are just making use of the function, all your project has to do to encrypt some text is this:

Like the caesar function, ascii_shift also has arguments for a key and text parameters that accept strings. Unlike the caesar function, the string you pass to text can contain all printable characters including spaces, digits, punctuation, and other keyboard symbols. The ascii_shift function also has a for letter in text loop that does the shift operation on each character and adds it to a result string, which was declared as an empty string variable before the loop.

Inside that function, the main difference is this statement:

Those four blocks do the same job as these seven:

Unlike the Caesar cipher, which started with characters indexed as 0…25, the printable ASCII characters are in a range of 32…126. The modulus operator trick and negative value trick won’t work right if your alphabet doesn’t start with an index of 0. So, it has to subtract 32 before both the set ascii to (remainder of (ascii/94)) block and the if (ascii < 0) then add 94 block, then add 32 afterwards. Here is a breakdown of each step:

  1. Get the letter’s ASCII value with set ascii to (char code (letter) at (0))
  2. Subtract 32 to shift the index from 32…126 to 0…93 with set ascii to (ascii – 32). 
  3. Add the key with set ascii to (ascii + key).
  4. Circular shift any index values above 93 around to continue from zero with set ascii to (ascii % 94).
  5.  Check if the ascii value is negative or positive with the if (ascii < 0) then.
  6. If it is negative, circular shift any index values above 0 around to continue from 93 with change ascii by 94
  7. Make sure the result goes back to the 32…126 range with set ascii to (ascii + 32). 

Substitution Ciphers

Another encryption example is the substitution cipher. With a substitution cipher, each character in an alphabet maps to a cryptabet with different characters in the same position. The simplest example of this is the Atbash or reverse-alphabet cipher. 

Alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cryptabet: ZYXWVUTSRQPONMLKJIHGFEDCBA

Example project: substitution_cipher_atbash

  • Enter substitution_cipher_atbash, then flash it into the micro:bit.

  • Open the terminal, check that local echo is checked, and make sure your keyboard is set to CAPS LOCK. 
  • Try ABCD, the result should be ZYXW.
  • Now, try ZYXW, the result should be ABCD.

How It Works – substitution_cipher_atbash

Your code has to use set result to (atbash(plaintext)) to get the ciphertext—no key required.

The atbash function has one parameter, text. The built-in key is the cryptabet, a reverse alphabet in this case. Like the other cipher functions, this one also declares an empty string named result to store the result.

Inside the loop that generates the ciphertext, it starts the same way, by finding the index of the letter in the alphabet with set index to ((alpha) find index of (letter)). What’s different is set result to (join (result) (char from(crypta) at (index))). This grabs the character with the same index in the cryptabet, and adds it to the result.

Example: Let’s say that letter is E. It’s index in the alphabet is 4. The character at crypta[4] is V, so V would be added to the result string.

Your Turn – Custom Cryptabet

Here is an alphabet that also includes digits, a space and some characters that would be useful for making a dictionary.

Alphabet: abcdefghijklmnopqrstuvwxyz 123456789:,{}’

  • Make a cryptabet by scrambling all 41 characters. 

Your Cryptabet: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

  • After making your custom cryptabet, substitute the alphabet and cryptabet into the Atbash function.
  • Rename it scrambled_alphabet.
  • Update the function call accordingly.
  • Name your project scrambled_alphabet_cipher.
  • Test to make sure that you can encrypt and decrypt this string: {‘start’ : 3, ‘after’ : ‘Liftoff! ‘}.

DISCUSSION FORUMS | PARALLAX INC. STORE

About | Terms of Use | Feedback: learn@parallax.com | Copyright©Parallax Inc. 2024


Source URL:https://learn.parallax.com/courses/cybersecurity-encryption-intro_makecode/
Links