Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 80 ยท Practice and Review

Practice: Fundamentals and Cryptography

Six hands-on cybersecurity exercises with solutions: rank risks, audit file hashes, sign tokens with HMAC, see why salts matter and why nonce reuse breaks ciphers.

Reading about security is not the same as thinking in it. These exercises cover the first two chapters of the course: risk, the core principles, hashing, message authentication and the basic ideas of encryption. Each exercise gives you a task and a hint, followed by a complete, runnable solution in Python on fake data.

The best way to use this page: read the task, try to write your own answer in the editor of a blank TryIt or in your own Python environment, and only then open the solution and compare. Where your approach differs, work out why. Then change the solution (break it on purpose, add a case) and watch what happens.

flowchart TD
    Q{"What do you need?"} --> I["Detect accidental or<br/>malicious change"]
    Q --> A["Prove the sender holds<br/>a shared secret"]
    Q --> C["Keep the content secret"]
    Q --> P["Let anyone verify, but only<br/>the owner sign"]
    I --> H["Hash (SHA-256)"]
    A --> M["MAC (HMAC)"]
    C --> E["Authenticated encryption"]
    P --> S["Digital signature"]

Choosing the primitive starts with the guarantee you need. Several exercises below are about not mixing these up.

Exercise 1: rank the risks

Task. A small company lists six risks, each with a likelihood and an impact on a 1 to 5 scale. Compute risk = likelihood x impact, sort the list from worst to best (use impact to break ties) and label each risk: 1 to 4 is Low, 5 to 9 Medium, 10 to 15 High and 16 to 25 Critical.

Hint. Sort with a tuple key, (-score, -impact). The ideas are in Threats, Vulnerabilities and Risk.

Python Solution 1: risk ranking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the printer ranks last even though an attacker could use it. Ranking is not a verdict that the low items are safe, it tells you where the next hour of effort pays most. Which principle would you apply first to the top item? (Defense in depth: multi-factor authentication, mail filtering and training together.)

Exercise 2: a file integrity audit

Task. You have a manifest of SHA-256 hashes recorded when a release was built. Later you scan the server. Write audit(manifest, current) that reports files that were modified, missing and unexpected. Then compare the hashes of two messages that differ by one character and count how many of the 256 bits differ.

Hint. Compare dictionaries by key. For bit counting, XOR the two hash values as integers and count the ones.

Python Solution 2: integrity manifest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

About half of the bits flip for a one-character change; that is the avalanche effect. It is also the catch of this design: an attacker who can change a file can usually change the manifest too. A plain hash list only helps if the manifest is stored (or signed) somewhere the attacker cannot reach.

Exercise 3: a single-purpose signed token

Task. Write make_token(purpose, user, issued, key) and check_token(token, purpose, key, now, max_age) using HMAC-SHA-256. The token must be bound to a purpose (so a password-reset token cannot be used to confirm an email address) and to an issue time (so it expires after max_age seconds). Test four cases: genuine, wrong purpose, expired and tampered user name.

Hint. Sign purpose|user|issued and compare with hmac.compare_digest. Review HMAC and Message Authentication if needed.

Python Solution 3: purpose-bound token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details to keep: the separator is forbidden inside fields so that alice|1 cannot be confused with a different split, and the time check happens only after the tag is confirmed to be valid.

Exercise 4: why a bare hash is not a password store

Task. An attacker steals a table of unsalted SHA-256 hashes of 4-digit PINs. Build a lookup table of all 10,000 possible PINs and recover the PIN for each stolen hash. Then repeat the theft against salted hashes (a random salt stored beside each hash) and show that the same lookup table no longer works.

Hint. A table maps sha256(pin) to pin. A salt changes what is hashed, so you would need a new table per user.

Python Solution 4: salts versus lookup tables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The salt defeats precomputed tables and hides that two users chose the same PIN, but it cannot rescue a tiny secret: 10,000 guesses is nothing, even per user. Real password storage adds a deliberately slow function and long, unpredictable secrets. That is the subject of Password Storage Done Right.

Exercise 5: why a nonce must never repeat

Task. Below is a toy stream cipher (a keystream made from SHA-256 and a counter). Encrypt two messages with the same key and nonce. Show that XOR-ing the two ciphertexts removes the key completely and leaves plaintext1 XOR plaintext2; then use a guessed phrase in the first message to read part of the second. Finally repeat with different nonces and show the relationship disappears.

Hint. (p1 ^ k) ^ (p2 ^ k) = p1 ^ p2. This toy cipher is for learning only, never use hand-made ciphers; see Symmetric Encryption and Modes.

Python Solution 5: keystream reuse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is exactly why AES-GCM and ChaCha20-Poly1305 are so unforgiving about repeated nonces: one repeat lets an attacker cancel the key out and then recover text by guesswork. Use a library that generates nonces for you, or a counter you can prove never repeats.

Exercise 6: spot the fake protection

Task. A web app stores a "secure" cookie that is just Base64 of JSON. Decode it, show that you can forge an admin cookie in two lines, and then fix the design with an HMAC so that the forgery is detected.

Hint. Base64 is an encoding, not a protection (Cryptography in Plain Language). The fix is integrity, so sign the exact bytes you send.

Python Solution 6: forging and fixing a cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fix gives integrity, not secrecy: the user can still read the cookie. If the content must be hidden, encrypt it (with authentication), or better, keep the data on the server and hand out only an unguessable session ID, as you saw in Sessions, Cookies and JWTs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A risk has likelihood 2 and impact 5, another has likelihood 3 and impact 3. Which scores higher on likelihood x impact, and what is a sensible tie-break for equal scores?

    2 x 5 = 10 and 3 x 3 = 9. When scores tie, ranking by impact first is common because a rare disaster is usually worse than a frequent nuisance.
  2. 2. Why does a hash manifest of your release files not stop a skilled attacker who has write access to the server?

    A plain hash proves nothing about who produced it. Integrity checks need a trusted place for the reference values, or a signature or MAC.
  3. 3. What does binding a purpose string into the HMAC protect against?

    If the purpose is part of the signed data, a password-reset token fails validation as an email-confirmation token because the expected tag differs.
  4. 4. Two ciphertexts were produced with the same key and nonce in a stream cipher. What can an attacker compute without the key?

    The identical keystream cancels out when the ciphertexts are XORed, leaving the XOR of the plaintexts. Known or guessable phrases then reveal the rest.

Summary

  • Rank risks by likelihood times impact, state your tie-break, and use the ranking to decide where to spend effort first.
  • A hash detects change but proves no origin; keep reference hashes out of the attacker's reach, or use a MAC or signature.
  • Bind purpose and time into signed tokens, compare tags in constant time and check the tag before parsing the data.
  • Salts defeat precomputed tables and hide duplicates, but a small secret space stays weak; real passwords need slow hashing.
  • Never reuse a nonce with the same key; it turns encryption into an XOR puzzle.
  • Base64 is an encoding. Integrity needs a MAC; secrecy needs authenticated encryption.

Next: Practice: Web Application Security, where the exercises move to injection, XSS, CSRF, validation and headers.