Skip to content

Introduction to Cryptography

Learning Goals

After these two weeks, you will be able to

  • Understand what cryptography is, why we need it, and where it is used
  • Explain the difference between symmetric and asymmetric cryptography
  • Explain the difference between a block cipher (AES) and a stream cipher (ChaCha20)
  • Understand what hashing (SHA-256) is and how it differs from encryption
  • Explain what a message authentication code protects against
  • Explain the basic idea behind the Diffie-Hellman key exchange
  • Explain how public-key cryptography such as RSA is used for encryption and digital signatures
  • Lecture slides: PDF

Preparation

Go through the material below before the first lab (week 46).

How much do I need to prepare?

This page is the preparation for both crypto labs, so it is a bit longer than for the other units. You do not need to study everything in detail to pass the RAT: read the text, look at the figures and watch the four short videos shown directly on the page. Expect to spend about an hour.

The collapsed boxes (Optional video and For the curious) go deeper. They are useful when you work on the labs, but not needed for the RAT.

What is cryptography?

Cryptography is the science of protecting information so that we can achieve properties such as confidentiality (only the intended recipient can read a message; achieved with symmetric or asymmetric encryption) and authenticity and integrity (the message really comes from who it claims to, and has not been changed on the way; achieved with message authentication codes or digital signatures). Cryptography covers many other things as well, but these are the properties we will focus on.

Encryption

Encryption is a key part of cryptography. It turns readable information, the plaintext, into a secret code called the ciphertext, to keep it confidential.

It does this using an algorithm called a cipher and a secret value called a key. Without the key, you can neither decrypt the ciphertext nor learn anything about the plaintext. Note what encryption does not do: it does not by itself stop someone from changing the ciphertext on the way. For that we need something else (see Message authentication codes below).

Symmetric Encryption

In symmetric encryption (also known as secret-key encryption), the same key is used for both encryption and decryption (this is the symmetry). In the picture below, you can see a plaintext being encrypted with a secret key, resulting in a ciphertext. The ciphertext can then be decrypted using the same secret key, yielding the same plaintext we started with.

Symmetric encryption

A classic cipher: the Caesar cipher

Classical ciphers form the historical foundation of modern cryptography. The Caesar cipher is a simple substitution cipher in which each letter is shifted by a secret number of positions. The picture shows a shift of 3, so A becomes d. In Lab 1 you will implement it, and then break it.

Caesar cipher wheel

Watch the following video to learn how this works:

Modern symmetric ciphers: block ciphers (AES) and stream ciphers (ChaCha20)

The Caesar cipher has only 25 possible keys (shifts). Modern ciphers use keys of 128 or 256 bits (far too many to try them all) and are designed so that the ciphertext looks like random noise. The two most widely used today are AES (a block cipher: it encrypts the data 16 bytes at a time) and ChaCha20 (a stream cipher). When you visit a website with the padlock in the address bar, your browser and the server use one of these two to protect the traffic (TLS 1.3 uses AES-GCM or ChaCha20-Poly1305).

A stream cipher works a lot like a modern version of a one-time pad. From the key it generates a long, random-looking sequence of bytes, the keystream, and encryption is simply XOR: every byte of the plaintext is XORed with the corresponding byte of the keystream. Because XOR undoes itself, decryption is the same operation with the same keystream. This is all you need to know about ChaCha20 for the labs, and it is why the ChaCha20 code you are given in Lab 2 has only an encrypt function. (In real use, the keystream also depends on a number that is changed for every message, so that no two messages are ever XORed with the same keystream. You will see in Lab 2 why that matters.)

Stream cipher: keystream XOR plaintext

Block cipher versus stream cipher

Optional video: the one-time pad

The one-time pad is the idea every stream cipher is built on. This short video shows why XOR with a random keystream is perfectly secret, and why the keystream must never be reused:

Optional video: how big is a 256-bit key?

How big is a 256-bit key, really? Big enough that trying all of them is not a question of better hardware:

Hashing

Hashing is a way to create a fingerprint of some information, whether it is a short text like "ABC" or a file of many gigabytes. A hash function always outputs a string of a fixed size (for example 256 bits) no matter the input, and it is deterministic, so the same input always produces the same output. Change a single letter of the input, and the output changes completely: the SHA-256 hash of hello starts with 2cf24dba…, while the hash of hellp starts with fdd7585e….

Hash function

Hash functions have some important security properties: 1) they are one-way, so that the output looks random and it is practically impossible to find out what the input was, and 2) they are collision resistant, meaning that it is practically impossible to find two different values x and y such that the hashes h(x) and h(y) are equal.

Optional video: hash functions and their security

This video explains what a hash function is, what the one-way and collision-resistance properties mean, and why they matter:

Optional video: how (not) to store passwords

The most common everyday use of hashing is storing passwords. This video shows what goes wrong when it is done badly, and why one-way is the property that saves you:

Message authentication codes (MAC)

Encryption hides the content of a message, but an attacker who sits between you and your bank can still change the ciphertext, and the bank has no way of telling whether the garbled result is your mistake or an attack. A message authentication code (MAC) fixes this. The sender computes a short tag from the message and a secret key (in the simplest case, by hashing them together) and sends the tag along with the message. The receiver, who knows the same key, recomputes the tag and compares. If anything in the message was changed, the tags no longer match, and nobody without the key can produce a valid tag for a message of their own.

Message authentication code

In Lab 1 you will build a MAC from SHA-256, and in Lab 2 you will put one on every radio packet between two micro:bits. (Real systems use a standardised construction called HMAC.)

Asymmetric (public-key) cryptography

In asymmetric cryptography (also known as public-key cryptography), every participant has two keys: a public key that can be given to anyone, and a private key that is kept secret. The two keys are mathematically linked, and what one of them does, only the other can undo. This solves the key-distribution problem of symmetric cryptography and gives us two tools: a way for two parties to agree on a secret key over an open channel (Diffie-Hellman), and public-key encryption and digital signatures (RSA). In practice the two worlds are combined: asymmetric cryptography is used to establish a symmetric key, and the fast symmetric cipher then protects the data.

The following video explains the idea of a public and a private key, and how the same key pair is used both for encryption and for digital signatures:

Key exchange: Diffie-Hellman

Symmetric ciphers are fast, but they have a chicken-and-egg problem: both parties need the same secret key before they can start. So how do they agree on it when everyone can listen in? The Diffie-Hellman key exchange (1976) solves exactly this, and it is what you will implement in both labs.

The idea, with a prime number p and a number g that everyone knows:

  1. Alice picks a secret number a and sends Bob A = ga mod p.
  2. Bob picks a secret number b and sends Alice B = gb mod p.
  3. Alice computes K = Ba mod p; Bob computes K = Ab mod p. Both get the same number, because (gb)a = (ga)b = gab.

An eavesdropper sees g, p, A and B, but to find K they would have to recover a or b. This is the discrete logarithm problem, which is believed to be practically impossible when p is a few thousand bits long. A tiny example with p = 23 and g = 5: if Alice picks a = 6 she sends A = 56 mod 23 = 8; if Bob picks b = 15 he sends B = 515 mod 23 = 19; both then compute K = 196 mod 23 = 815 mod 23 = 2. (With such a small p you can of course just try all 22 possible values of a; you will do exactly that in Lab 1.)

Diffie-Hellman key exchange

If the formulas feel abstract, the classic paint analogy says the same thing: mixing colours is easy, separating them again is hard.

Diffie-Hellman paint analogy

This video builds the key exchange up from the paint analogy to the actual numbers, following the same steps as the list above:

Optional video: the man-in-the-middle attack

Diffie-Hellman alone does not tell Alice who she is talking to. This video shows the man-in-the-middle attack that follows, and why the key exchange is combined with digital signatures (next section) in practice:

Public-key encryption and digital signatures: RSA

With RSA, Bob picks two large primes p and q and publishes n = p·q together with a number e as his public key; his private key d can only be computed by someone who knows p and q. Anyone can now encrypt a message for Bob with the public key, but only Bob, with the private key, can decrypt it:

Public-key encryption

Turned around, the same key pair gives a digital signature: Alice signs a message with her private key, and anyone can verify the signature with her public key. A valid signature shows that the message really comes from Alice and has not been changed: like a MAC, but one that anyone can check, and that only Alice could have produced.

Digital signature

The security of RSA rests on factoring: everyone can see n, but recovering p and q from a 2048-bit n is infeasible.

For the curious: the RSA maths

You do not need this for the RAT or the labs.

RSA

Optional video: RSA with real numbers

if you want to see the maths worked through with real numbers, this video does exactly that, from choosing the primes to encrypting and decrypting a message:

Looking ahead: quantum computers

a large quantum computer would break both Diffie-Hellman and RSA (but not AES, ChaCha20 or SHA-256). New public-key algorithms were standardised by NIST in 2024, and the migration to them has started. More about that in the lecture.

Optional Material

If you find cryptography an interesting topic, we recommend the book Serious Cryptography by Jean-Philippe Aumasson (2nd edition, No Starch Press, 2024). It covers everything in this unit, and much more, in a very readable way.

A crash-course video covering several of the elements in the preparation material, as well as some other interesting parts:

Teamwork

The cryptography unit spans two lab Fridays, and both labs are done in Jupyter notebooks that you also hand in:

Date Lab What you need
Week 46 Friday 13 November Crypto Lab 1: Introduction. Caesar cipher, primes and randomness, Diffie-Hellman, hash functions and MACs, all in Python A laptop
Week 47 Friday 20 November Crypto Lab 2: Putting it all together. Encrypted and authenticated radio messages between two micro:bits, with a Diffie-Hellman key exchange A laptop, two micro:bits per team, and your Lab 1 notebook. The code you write runs on the micro:bits via the micro:bit Python Editor, as in the IoT unit

Open the notebooks on NTNU's JupyterHub with these links (they clone the lab repository into your home directory the first time, and open the notebook):

If the links do not work

Log in at jupyter.ntnu.no, open the Git menu, choose Clone a Repository and paste https://git.ntnu.no/ie-iik/ttm4175-crypto-lab.git. You will find lab1.ipynb and lab2.ipynb in the new folder. You can also run the notebooks on your own computer with any recent Python and Jupyter.

Working in Jupyter

  • Run the cells in order


    Start at the top and press Shift+Enter to run a cell and move on. A cell that uses a function from an earlier cell fails if that cell has not been run yet.

  • Start from a clean slate


    If things get confusing, Kernel → Restart Kernel and Run All Cells clears everything and runs the notebook again from the top.

  • Use the self-checks


    Many tasks have a self-check cell that gives a readable error until your solution is correct. When it passes, move on.

  • Read Troubleshooting first


    Both notebooks start with a Troubleshooting section that covers the most common errors. Check it before you ask for help.

  • Lab 2: paste your code back


    You write and test the code on the micro:bits, but every finished function must also be pasted into the notebook. The notebook is what you hand in.

  • Answer the questions


    Read all instructions carefully so you do not miss a task. Each written question is followed by an answer cell: double-click it and write your answer.

This is what a question and its answer cell look like in JupyterLab:

A question followed by an empty answer cell in JupyterLab

Report

Report 3 covers the two cybersecurity labs and the two cryptography labs, and is handed in on Canvas by Friday 27 November, 23:30. For the cryptography part, do as follows:

  1. Describe in the report how you solved each part of the two labs: a short text per part (what you did, how it works, what was difficult), plus the usual reflection and feedback at the end. You may reuse the answers you wrote in the notebooks.
  2. Attach the notebooks as .ipynb files (one per lab) to the Canvas submission, so that the teaching assistants can run them and see your code. Before you download a notebook (File → Download), run it from the top (Kernel → Restart Kernel and Run All Cells) and check that every cell runs without errors and that all answer cells are filled in.

The general report requirements (PDF, file name, team submission) are on the Reports page.