The previous lesson left an explicit debt. We talked about hashes without saying what they are, we used HMAC without explaining it, we accepted as magic that a passkey has a private key that never leaves the device and a public one that does, and we recommended encrypting data at rest without specifying what exactly that means. All that machinery — well-stored passwords, one-time codes, FIDO2 keys, the encryption of an AWS volume — rests on a single discipline, and it starts here.

This lesson does not aim to turn you into a cryptographer. It aims at something more useful and far more achievable: that you should be able to make correct decisions about cryptography without having to understand the underlying mathematics. That you should know why AES-256 in a badly chosen mode can leave your data in plain sight, why reusing a number that looks harmless breaks the whole encryption, how two people who have never met agree on a secret key across a channel somebody is listening to, and why the key Marta Ruiz left written in MiRutalia's config.py is a bigger problem than any algorithm she might choose.

The rule that presides over the whole lesson is this: your job is not to invent cryptography, it is to use well the cryptography that already exists. And using it well consists, almost always, of making three or four decisions and not getting any of them wrong.

  1. What cryptography solves and what it does not

First of all it is worth marking out the ground, because the most expensive mistake with cryptography is not choosing the wrong algorithm: it is believing it solves a problem it does not solve.

What it does solve

Property (from those we saw in 02-01) Cryptographic tool Example at Rutalia
Confidentiality Encryption The customer database dump that travels to AWS is unreadable without the key
Integrity Hashes, MACs, signatures Detecting that the rates file has been altered
Authenticity Digital signatures, certificates, MACs Checking that the message really comes from the supplier
Non-repudiation A digital signature with a private key The customer cannot deny having placed the order

What it does not solve

This list matters as much as the previous one:

  • It does not replace access control. If an attacker exploits MiRutalia's IDOR and the application serves them the data, the application serves it decrypted, because that is what it has the key for. Encrypting the database does not stop hypothesis H4. This is misunderstanding number one.
  • It does not protect data in use. The moment the program works with it, it is in the clear in memory.
  • It does not fix a badly stored key. AES-256 with the key written in the source code offers the security of an unprotected folder. Cryptography turns the problem of protecting the data into the problem of protecting the key; if you gain nothing in that exchange, you have gained nothing.
  • It does not protect against a legitimate user abusing their access. Hypothesis H3 — the insider who takes the customer book — is immune to encryption: the insider sees the decrypted data because they are entitled to see it.
  • It does not guarantee availability. Quite the opposite: as we saw in 02-01, it adds the risk of losing the key, and with it the data.
  • It does not make an insecure application secure. "It runs over HTTPS" does not mean the application is well built; it means the channel is protected.

A useful formulation. Cryptography protects data beyond the reach of your access controls: when it travels over a network you do not control, when it rests on a disk somebody could steal, when it sits at a provider that is not yours. Inside your application, authorisation is what rules.


  1. Terminology and Kerckhoffs's principle

Term Definition In one phrase
Plaintext The original, readable information IBAN ES12 3456 7890
Ciphertext The result of encrypting 8f3a91c04b...
Encrypt Transform plaintext → ciphertext The operation of protecting
Decrypt Transform ciphertext → plaintext, with the key The authorised operation of recovering
Crack / break Recover the plaintext without the key What the attacker does
Key The secret that parameterises the transformation The only thing that must be secret
Algorithm (cipher) The mathematical procedure AES, RSA, ChaCha20
Cryptanalysis The study of how to break ciphers The attacker's discipline

Kerckhoffs's principle

Formulated in 1883 by Auguste Kerckhoffs, it is the founding idea of modern cryptography:

A cryptographic system must be secure even if everything about it is public knowledge, except the key.

Or in Claude Shannon's formulation: "the enemy knows the system".

The practical consequences are enormous and very concrete:

  1. Good algorithms are public. AES was selected through an open international competition in which every candidate was published and everybody tried to break them for years. Its security does not lie in secrecy, it lies in having survived scrutiny.
  2. "Security through obscurity" is not security. A supplier who tells you "we use a proprietary algorithm we cannot disclose" is telling you that nobody has reviewed it. In cryptography that is bad news, not an advantage.
  3. Only the key is secret, which is why all the management effort concentrates on it (section 10).
  4. Changing the key is cheap; changing the algorithm is enormously expensive. If your security depends on the secrecy of the algorithm, the day it leaks you have to rebuild the system.

A corollary worth tattooing on yourself, and which we will repeat in section 11: do not invent your own algorithm. Cryptography is one of the very few areas of computing where code that "works" can be completely broken with no test that will reveal it.


  1. Symmetric encryption: the shared key

In symmetric encryption, the same key encrypts and decrypts. It is the oldest and the most intuitive model: a box with a lock and two copies of the key.

graph LR
    P["Plaintext<br/>'Rates 2026'"] --> C["Encrypt<br/>AES"]
    K["Secret key<br/>(the same one)"] --> C
    C --> X["Ciphertext<br/>8f3a91c0..."]
    X --> D["Decrypt<br/>AES"]
    K --> D
    D --> P2["Plaintext<br/>'Rates 2026'"]
    style K fill:#fef7e0,stroke:#b06000

AES

AES (Advanced Encryption Standard) has been the reference symmetric algorithm since 2001. It is a block cipher: it processes information in 128-bit (16-byte) blocks and applies several rounds of substitutions and permutations controlled by the key.

The available key sizes:

Size Rounds Comment
AES-128 10 Sound. Sufficient for the vast majority of uses
AES-192 12 Little used
AES-256 14 The de facto standard when there are regulatory requirements or a long-term margin is wanted

One honest clarification worth being clear about: AES-128 is not "broken" nor is it "the cheap option". A brute-force attack against a 128-bit key is beyond any foreseeable computing capability. The preference for AES-256 comes down to regulatory requirements, to custom and to leaving margin against future advances — including quantum ones, which are analysed in Quantum Computing and Post-Quantum Cryptography. The extra cost is small, so use AES-256 and forget about it: that is not where you are going to fail.

Another symmetric algorithm you will see more and more is ChaCha20-Poly1305, especially on devices without hardware acceleration for AES (older phones, the fleet's tablets, IoT devices such as the A006 probes). It is equally sound and faster in those environments.

Advantages and drawbacks

Advantages Drawbacks
Very fast: encrypts gigabytes per second, with acceleration in modern processors The key has to be shared beforehand, and that is the hard problem (section 7)
Short keys (16 or 32 bytes) The number of keys grows quickly: for N parties communicating with one another you need N(N-1)/2 keys
Well studied and widely implemented On its own it provides no non-repudiation: if two people have the key, either could have encrypted

That last point deserves attention. If Laura and Diego share a key, a message encrypted with it proves that one of the two wrote it, not which one. For non-repudiation you need asymmetric cryptography.


  1. Modes of operation: why ECB is insecure

AES encrypts 16-byte blocks. But real data is bigger: a file, a CSV of 400 customers, a database. The mode of operation is the recipe that says how to chain the encryption of many blocks.

And here lies one of the most important traps in applied cryptography: choosing the wrong mode nullifies the security of the algorithm, however good it is.

ECB: the mode you must never use

ECB (Electronic Codebook) is the naive approach: encrypt each 16-byte block separately, with the same key.

Plain:    [block1 ][block2 ][block3 ][block4 ]
             v        v        v        v     (same key, independent)
Cipher:   [ciph_1 ][ciph_2 ][ciph_3 ][ciph_4 ]

The flaw is obvious the moment it is stated: identical plaintext blocks produce identical ciphertext blocks. The encryption does not hide the patterns in the data, it merely substitutes its content.

The classic example that makes this visible is an image. If you take a bitmap with a drawing on a uniform background and encrypt it with AES-256 in ECB mode, the result still shows the drawing: every area of background always produces the same ciphertext block, so the outlines remain perfectly recognisable. With a correct mode, the result is noise indistinguishable from random. It is the most compelling visual demonstration in applied cryptography: the same key, the same unbreakable algorithm, and a different mode is the difference between protecting and protecting nothing at all.

With Rutalia's data the problem is just as serious although less spectacular. Imagine the shipments table encrypted field by field with ECB:

estado_envio (plain)    estado_envio (encrypted with ECB)
--------------------    ---------------------------------
ENTREGADO               a91c3f07b2d45e68
ENTREGADO               a91c3f07b2d45e68      <- identical
EN_REPARTO              7d42e0a9c1b38f50
ENTREGADO               a91c3f07b2d45e68      <- identical
INCIDENCIA              3b8f1d6c4a09e275

Without knowing the key, an attacker deduces how many distinct statuses there are, which is the most frequent (almost certainly ENTREGADO) and, cross-referencing with public information, can label them all. They have "decrypted" the column without breaking AES.

The modes that do work

Mode How it chains Authenticated Parallelisable Recommendation
ECB It does not chain No Yes Never. It only appears in examples of what not to do
CBC Each block is combined (XOR) with the previous ciphertext No Not when encrypting Acceptable only if a separate MAC is added. Historically the origin of many padding vulnerabilities
CTR Turns the block cipher into a stream cipher by encrypting a counter No Yes The basis of GCM; do not use it alone without authentication
GCM CTR + built-in authentication Yes Yes The default option for new data
ChaCha20-Poly1305 Stream cipher + authentication Yes Yes The default alternative, better without AES acceleration

CBC solves ECB's problem by introducing chaining: each block is combined with the encrypted result of the previous one, so that identical blocks produce different outputs. The first is combined with a random IV (initialisation vector). It is a correct mode as far as confidentiality goes, but it has two serious drawbacks: it is not parallelisable when encrypting and, above all, it does not detect tampering. That shortcoming has been the cause of a long family of practical vulnerabilities, and it is why authenticated encryption is preferred today.

Rule of thumb. If you have to choose a mode, choose AES-GCM (or ChaCha20-Poly1305). If you come across CBC in an existing system, check whether there is a MAC accompanying it; if there is not, you have an integrity problem, and not merely a theoretical one.


  1. Authenticated encryption (AEAD), IVs and nonces

Why authentication is needed

Imagine the cold store IoT probes (A006) send the temperature encrypted with AES-CTR without authentication. An attacker cannot read the message, but they can alter it: in a stream cipher, changing one bit of the ciphertext changes exactly the corresponding bit of the plaintext. Without knowing the key, they can turn -18 into another number and make the system believe the cold store is cold when it is not.

That attack is impossible to detect with an unauthenticated mode. Hence the concept of AEAD (Authenticated Encryption with Associated Data): encryption that, as well as concealing, produces an authentication tag guaranteeing the message has not been altered. On decryption, if the tag does not match, the operation fails instead of returning rubbish.

AEAD provides three things at once:

  1. Confidentiality of the ciphertext.
  2. Integrity and authenticity of the ciphertext, through the tag.
  3. Integrity of associated data that travels in the clear but must not be alterable: headers, identifiers, version numbers. An example at Rutalia: the probe identifier can travel in the clear (the system needs it for routing) but authenticated, so that nobody can relabel a reading from the Sevilla probe as if it came from Valencia.

IVs and nonces: the mistake of reusing them

An IV (initialisation vector) or nonce (number used once) is a value that accompanies the key so that encrypting the same message twice with the same key produces different results.

Three properties you have to understand properly, because they are constantly confused:

  1. It is not secret. It is transmitted or stored in the clear alongside the ciphertext. It does not need protecting.
  2. It must be unique for each message encrypted with the same key. This is the rule that gets broken.
  3. In some modes it must also be unpredictable (CBC), while in others it is enough for it to be unique (GCM, CTR).

What happens if a nonce is repeated in GCM, which is the case you are going to meet:

  • The immediate consequence is that the XOR of the two plaintexts leaks, which allows substantial information about both to be recovered without knowing the key.
  • And the serious consequence: the authentication key can be compromised, which lets the attacker forge messages that will look genuine. In GCM, repeating a nonce does not degrade security: it destroys it.

The safe way to generate them:

import os
nonce = os.urandom(12)   # 96 bits, the recommended size for AES-GCM
  • os.urandom uses the operating system's cryptographically secure random number generator. Never use random.randint or anything like it: Python's random module is predictable by design and is meant for simulations, not for security.
  • 12 bytes is the standard size for GCM: it is optimised for that case and avoids an internal derivation step.
  • With 96-bit random nonces, the probability of a collision is negligible up to a very large number of messages per key. If you are going to encrypt thousands of millions of messages with the same key, use a counter rather than random values, or rotate the key.

And the golden rule, which sums up the whole section:

One key, one nonce, one message. If the same (key, nonce) pair is used twice, consider both messages compromised.


  1. Asymmetric encryption: two keys, two uses

Asymmetric, or public-key, cryptography introduces an idea that in 1976 was revolutionary: two mathematically related keys, such that what one closes only the other opens.

  • The public key can be published, emailed, put on a website. There is no problem at all in everybody knowing it.
  • The private key never leaves its owner. It is the secret.

The relationship between the two is such that, knowing the public one, it is computationally infeasible to deduce the private one.

The two uses, which are opposites and get confused

This is the part people find hardest at first, and it is worth nailing down with a table:

Use Encrypted/signed with Decrypted/verified with What it achieves Who can do it
Confidentiality The recipient's public key The recipient's private key Only the recipient can read it Anybody can send them something secret
Signature The sender's private key The sender's public key Authenticity, integrity, non-repudiation Only the owner can sign; anybody can verify

One way to remember it:

You encrypt with someone else's public key (so that only they can read it). You sign with your own private key (so that everybody knows it was you).

graph TD
    subgraph "CONFIDENTIALITY"
        A1["Laura writes to Marta"] --> A2["Encrypts with Marta's<br/>PUBLIC key"]
        A2 --> A3["Only Marta decrypts<br/>with her PRIVATE key"]
    end
    subgraph "SIGNATURE"
        B1["Laura publishes a notice"] --> B2["Signs with her<br/>PRIVATE key"]
        B2 --> B3["Everybody verifies with<br/>Laura's PUBLIC key"]
    end
    style A2 fill:#e8f0fe,stroke:#1a73e8
    style B2 fill:#e6f4ea,stroke:#137333

(The detailed mechanism of the digital signature, exactly what it guarantees and how public keys are distributed reliably through certificates is the content of Hashes, Digital Signatures and Certificates (PKI).)

RSA and elliptic-curve cryptography

Aspect RSA ECC (elliptic curve)
Year 1977 Proposed in 1985, in mass use since the 2000s
Based on The difficulty of factoring large numbers The difficulty of the discrete logarithm on elliptic curves
Size for equivalent security 2048 bits (today's minimum), 3072-4096 for the long term 256 bits (curve P-256 or Curve25519)
Signing speed Slow Fast
Verification speed Fast Fast
Size of keys and signatures Large Small
Best suited to Compatibility with existing systems Phones, IoT, modern TLS, passkeys

The figure that sums up the comparison: a 256-bit ECC key offers roughly the same security as a 3072-bit RSA one. That is why the FIDO2 keys and passkeys we saw in 02-03 use elliptic curves: less computation, less battery, smaller keys and signatures.

A practical recommendation for 2026: ECC for new systems; RSA of at least 2048 bits if RSA has to be used for compatibility. RSA of 1024 bits is obsolete and must not be accepted.

The performance problem

Asymmetric cryptography is two to three orders of magnitude slower than symmetric. Encrypting a 500 MB file with RSA would be unworkable in practice; besides, RSA can only encrypt messages smaller than its key (around 190 bytes with RSA-2048 and OAEP padding).

That limitation is not a defect: it is the reason hybrid encryption exists (section 8).


  1. The key exchange problem and Diffie-Hellman

The problem

Symmetric encryption is fast and sound, but it requires the two parties to already share a key. And there the paradox appears: to agree on the key you have to communicate, and to communicate securely you need the key.

For centuries this was solved physically: couriers, code books, briefcases. It does not scale. MiRutalia cannot send a courier to each of its 400 customers.

The solution: Diffie-Hellman

In 1976, Whitfield Diffie and Martin Hellman published a method for two parties to agree on a shared secret across a completely public channel, without having agreed on anything secret beforehand.

The paint analogy

It is the clearest way to understand it:

  1. Laura and Marta publicly agree on a base colour, say yellow. Everybody can see it.
  2. Each secretly chooses a colour of her own: Laura red, Marta blue.
  3. Each mixes the public colour with her secret one and sends the mixture over the public channel: Laura sends orange (yellow+red), Marta sends green (yellow+blue).
  4. Each then adds her own secret colour to the mixture she received: Laura makes orange... no, she makes green+red; Marta makes orange+blue. Both obtain the same final mixture: yellow+red+blue.
  5. An eavesdropper has seen the yellow, the orange and the green. To obtain the final mixture they would need to separate a mixture into its components, which is the hard operation.

The mathematical property that makes this possible is commutativity: the order in which the colours are mixed makes no difference. And what makes it secure is that mixing is easy and separating is hard.

With small numbers

Let us go through the same process with arithmetic. We use tiny numbers so that it can be followed by hand; in reality they have hundreds or thousands of bits.

Public parameters (everybody sees them):

  • A prime number p = 23
  • A base g = 5

Step 1 — Private secrets:

  • Laura chooses a = 6 (nobody else knows it).
  • Marta chooses b = 15 (nobody else knows it).

Step 2 — Public values:

  • Laura computes A = g^a mod p = 5^6 mod 23. 5^6 = 15625; 15625 mod 23 = 8. → A = 8, and she sends it.
  • Marta computes B = g^b mod p = 5^15 mod 23. 5^15 mod 23 = 19. → B = 19, and she sends it.

Step 3 — Shared secret:

  • Laura computes s = B^a mod p = 19^6 mod 23 = 2
  • Marta computes s = A^b mod p = 8^15 mod 23 = 2

Both obtain s = 2, and that value has never travelled over the channel.

What the eavesdropper has seen: p=23, g=5, A=8, B=19. To obtain s they would have to solve 5^x mod 23 = 8, that is, work out that x = 6. That is called the discrete logarithm problem, and with a prime of 23 you solve it by trial. With a 2048-bit prime, you do not solve it.

You can check it for yourself:

# diffie_hellman.py — teaching demonstration with small numbers
p, g = 23, 5          # public

a = 6                 # Laura's secret
b = 15                # Marta's secret

A = pow(g, a, p)      # pow(base, exp, mod) = (base**exp) % mod, efficiently
B = pow(g, b, p)
print(f"Laura sends A={A}  |  Marta sends B={B}")   # A=8  B=19

s_laura = pow(B, a, p)
s_marta = pow(A, b, p)
print(f"Laura's secret: {s_laura}  |  Marta's secret: {s_marta}")  # 2 and 2
assert s_laura == s_marta

Python's pow(base, exp, mod) function performs modular exponentiation efficiently, without computing the gigantic intermediate number. With 2048-bit exponents, 5**a would have hundreds of digits; three-argument pow resolves it in milliseconds. It is the same algorithm the real libraries use.

The indispensable warning

Diffie-Hellman, on its own, does not authenticate. It is vulnerable to an attacker sitting in the middle who establishes an exchange with each party and poses as the other to both. That is why in practice DH always comes with authentication: a certificate, a signature, a previously known key.

That combination — agreeing the key with DH and authenticating the other party with a certificate — is exactly what the TLS protocol does, which you will see in Network Security Protocols. And there is a very valuable property worth naming here: when a DH key is generated ephemerally and differently for each session, you obtain forward secrecy: if somebody steals the server's private key tomorrow, they cannot decrypt the conversations recorded yesterday, because those session keys no longer exist anywhere.


  1. Hybrid encryption: why the two are combined

We now have the pieces and their limitations:

Symmetric Asymmetric
Speed Very fast Very slow
Message size Unlimited Limited and small
Key distribution A hard problem Solved
Non-repudiation No Yes

The virtues of one are the defects of the other. The obvious solution is to combine them, and that is hybrid encryption, which is what every real system uses in practice: TLS, encrypted email, encrypted files, backups.

graph TD
    A["Large file<br/>clientes.csv (40 MB)"] --> B["Encrypt with AES-256-GCM<br/>using a random session key"]
    K["Session key<br/>(32 bytes, random, single use)"] --> B
    K --> C["Encrypt the KEY with RSA/ECC<br/>using the recipient's public key"]
    B --> D["Encrypted file<br/>(40 MB)"]
    C --> E["Encrypted key<br/>(256 bytes)"]
    D --> F["Sent together"]
    E --> F
    style K fill:#fef7e0,stroke:#b06000

The complete process:

  1. A random symmetric session key is generated, used only once.
  2. The content — the large part — is encrypted with that key using AES-GCM. Fast.
  3. Only the session key — 32 bytes — is encrypted with the recipient's public key. Slow, but over 32 bytes it makes no difference.
  4. Everything is sent together.
  5. The recipient decrypts the session key with their private key, and with it decrypts the content.

That gives you the best of both worlds: the speed of symmetric and the ease of distribution of asymmetric. If you ever ask yourself "should I use symmetric or asymmetric?", the answer in a real system is almost always "both, like this".


  1. Data at rest, in transit and in use

Data has three states, and each is protected differently. It is a very useful framework for auditing an architecture.

State Where the data is How it is protected The situation at Rutalia
At rest Disks, backups, S3 buckets, laptops, tablets Full disk encryption, database-level encryption, object encryption The data centre servers have no disk encryption; nor do the tablets; bucket A009 would have to be verified
In transit Networks, the internet, the flat internal 10.10.0.0/16 network TLS, VPN, encrypted protocols The portal uses HTTPS; the legacy ERP talks in the clear inside the internal network
In use RAM while the program works A technological frontier: secure enclaves, homomorphic encryption Not applicable at Rutalia today

At rest

Two levels worth distinguishing, because they protect against different things:

  • Full disk encryption: protects against physical theft of the disk or the machine. When the system is booted and the disk mounted, the data is accessible to everything running on that machine. It protects against the thief, not against the remote attacker.
  • Application-level or column-level encryption: the specific value is encrypted before being stored. It also protects against anyone with access to the database but not to the application's keys. It costs more and complicates searching: you cannot do WHERE nombre LIKE '%Ruiz%' on an encrypted field.

A realistic priority for Rutalia: disk encryption on laptops and tablets first — they are the assets that genuinely get lost — and then the database server volume and the cloud storage.

In transit

The modern rule is that there is no trusted network. Rutalia has a flat 10.10.0.0/16 network with no segmentation: anyone who gains a foothold inside sees all the traffic that is not encrypted, including the legacy ERP's credentials.

(TLS, how its negotiation works and how it is configured correctly is studied in Network Security Protocols. Here it is enough to retain that TLS is an example of hybrid encryption with authentication through certificates.)

In use

This is the current frontier. While a program works with data, that data is in the clear in memory. Two lines of research, worth knowing about even if they do not apply to an SME today:

  • Secure enclaves / confidential computing: regions of memory encrypted by the processor itself, which neither the operating system nor the server administrator can access. Available in the major clouds.
  • Homomorphic encryption: allows operations on encrypted data without decrypting it — adding two encrypted numbers and obtaining the encrypted sum. Mathematically fascinating and still expensive in performance terms for general use.

  1. The key life cycle, HSMs and KMSs

Let us repeat the central idea: cryptography turns the problem of protecting the data into the problem of protecting the keys. If the key leaks, all the encryption is decorative; if the key is lost, so is the data.

The five phases

Phase What it involves Typical mistake
Generation Using a cryptographically secure random generator, with an appropriate length Generating keys with random, with the system clock or from a short password
Custody Storing it separately from the data it protects, with restricted and logged access The key next to the encrypted file; the key in the code repository
Rotation Replacing it periodically and re-encrypting, or encrypting new data with the new one Keys unchanged for eight years and known to three former employees
Revocation Rendering a compromised key useless and knowing which data has to be re-encrypted Having no inventory: not knowing what that key protected
Destruction Secure deletion of every copy once it is no longer needed Five-year-old backups that still contain the old key

A note on custody, because it is where things go wrong: if you store the key in the same place as the encrypted data, you have encrypted nothing. It is the equivalent of leaving the key in the lock. And yet the pattern "encrypted file and clave.txt in the folder next to it" is astonishingly common.

And another on destruction: deleting the key is the fastest and most reliable way to destroy encrypted data, and it is used deliberately. It is called crypto-shredding and it is a recognised technique for complying with the GDPR right to erasure on media where physical deletion is awkward → Personal Data Protection in Practice (GDPR).

HSMs and KMSs

Two acronyms that will come up in any conversation about keys:

HSM (Hardware Security Module) KMS (Key Management Service)
What it is A physical device that generates, stores and uses keys A service, normally in the cloud, for managing keys
Key property The private key never leaves the device: you send it data and it returns the result of the operation It centralises management, access control, logging and rotation
Physical protection Tamper-resistant: it self-destructs if anyone tries to open it Depends on the provider (which usually uses HSMs underneath)
Cost High Low, pay as you go
When Certificate authorities, financial institutions, strict regulatory requirements The sensible option for an SME like Rutalia

For Rutalia, which already has part of its infrastructure in AWS, the practical recommendation is to use the provider's key management service: keys are generated and held there, access is controlled with permissions, every use is logged and rotation is configured. It eliminates at a stroke the pattern of the key written in a configuration file, which is MiRutalia's real problem.

And the same principle we applied to accounts in 02-02 applies to keys: one key per purpose. The key that encrypts the backups is not the one that encrypts the customer CSV nor the one that signs the session tokens. That way, compromising one does not compromise everything.


  1. Classic cryptographic mistakes

These are the failings that turn up again and again in real audits. None of them is sophisticated; all of them are avoidable.

Mistake 1: inventing your own algorithm

The most serious and the most tempting for a curious programmer. The underlying problem is that a broken cipher works exactly as well as a secure one: it encrypts, it decrypts, the tests pass, and there is no symptom whatsoever. The only way to know whether an algorithm holds up is for many experts to attack it for years.

Disguised variants of the same mistake, all seen in real applications:

  • Applying XOR with a repeated password ("Vigenère cipher"). It is broken with statistical analysis.
  • Encoding in Base64 and calling it encryption. Base64 is not encryption: it is a reversible encoding with no key, anyone can undo it.
  • Combining two algorithms "to make it more secure". It can be less secure, not more.
  • Applying a good algorithm but with made-up parameters.

Mistake 2: using ECB

We have already seen it. It usually appears because it is the default mode in some older libraries and because it is the one that shows up in the first example in the documentation. If you see ECB in some code, that is an audit finding.

Mistake 3: keys embedded in the code

MiRutalia's case:

# config.py — BAD. This is what is in MiRutalia today.
DB_PASSWORD = "Rutalia_2024_Prod!"
SECRET_KEY = "mirutalia-secret-key-2024"
AES_KEY = b"0123456789abcdef0123456789abcdef"

Why it is serious, beyond the obvious:

  • It is in version control, and it stays there forever: even if the line is deleted tomorrow, the value remains in the Git history. Changing the file does not revoke the key.
  • Anybody with access to the repository — including former employees and the external vendor — has it.
  • If the repository is published by mistake, the key is indexed within minutes: automated tools exist that sweep public repositories looking for exactly this.
  • It cannot be rotated without deploying code.

The correct way:

# config.py — GOOD
import os

DB_PASSWORD = os.environ["MIRUTALIA_DB_PASSWORD"]   # fails at startup if unset
SECRET_KEY  = os.environ["MIRUTALIA_SECRET_KEY"]
  • os.environ["X"] raises an exception if the variable does not exist. That is deliberate: it is better for the application not to start than for it to start with a default key. The pattern os.environ.get("X", "default-key") is a trap that ends up in production.
  • The .env file with the real values is never committed: it goes in .gitignore.
  • And if a key has ever been in the repository, it has to be considered compromised and rotated; deleting it is not enough.

Mistake 4: weak randomness

import random
key = random.randint(0, 2**128)         # BAD: predictable

import secrets
key = secrets.token_bytes(32)           # GOOD: cryptographically secure

The random module uses a deterministic generator designed for simulations: by observing a handful of outputs you can reconstruct its internal state and predict every subsequent one. For keys, nonces, session tokens and recovery codes you have to use secrets in Python, os.urandom, or each language's equivalent.

It is a mistake that has caused real incidents of great reach, and the most insidious of all: the result looks perfectly random to the naked eye.

Mistake 5: reusing nonces or IVs

Already seen in section 5. It turns up when somebody fixes a constant IV "to keep things simple", or when a counter is used that resets when the service restarts.

Mistake 6: not authenticating the ciphertext

Using CBC or CTR without a MAC. It gives confidentiality without integrity, and opens the door to tampering. It is solved by using AEAD.

Mistake 7: confusing encryption with hashing or with encoding

Operation Reversible? Needs a key? What it is for
Encoding (Base64, URL) Yes, by anybody No Transporting data, not protecting it
Hash (SHA-256) No No Integrity, fingerprints
Encryption (AES) Yes, with the key Yes Confidentiality
KDF (bcrypt, Argon2) No No (it uses a salt) Storing passwords

Confusing them produces howling failures: "we encrypt the passwords with AES" is a design error — passwords are not encrypted, they are derived with a KDF, because the system must not be able to recover them — and "we store the token in Base64 for security" is no protection at all.


  1. Hands-on 1: encrypting a file with openssl

openssl is the Swiss army knife of command-line cryptography. It is on any Linux and on macOS, and knowing how to use it lets you check things without writing code.

Laura needs to send the negotiated rates file to the accountancy firm, and the channel is not trusted.

Encrypting

openssl enc -aes-256-cbc \
    -pbkdf2 -iter 600000 \
    -salt \
    -in tarifas_2026.csv \
    -out tarifas_2026.csv.enc

Option by option:

  • enc: the subcommand for symmetric file encryption.
  • -aes-256-cbc: the AES algorithm with a 256-bit key, in CBC mode. We will see in a moment why we are not using GCM here.
  • -pbkdf2: the key is not typed in raw, it is derived from a password using PBKDF2, which is a slow derivation function like the ones we saw in 02-03. Without this option, older versions of openssl use an obsolete and weak derivation. It is the option most often forgotten and the one that matters most.
  • -iter 600000: the number of derivation iterations. The higher it is, the more expensive it is for an attacker to try passwords. Six hundred thousand is a reasonable value today; it adds a fraction of a second to your operation and multiplies the attacker's work six hundred thousandfold.
  • -salt: adds a random salt (it is the default behaviour in modern versions, but stating it explicitly does no harm). It guarantees that encrypting the same file twice with the same password produces different outputs.
  • -in / -out: the input and output files.

openssl will ask for the password at the console. Do not use -pass pass:mypassword: it would be recorded in the shell history and visible in the process list to any user of the system. If you need to automate it, use -pass file:/protected/path or -pass env:VARIABLE.

Decrypting

openssl enc -d -aes-256-cbc \
    -pbkdf2 -iter 600000 \
    -in tarifas_2026.csv.enc \
    -out tarifas_2026_recovered.csv
  • -d indicates decryption. Every other parameter must match exactly those used for encryption: if you change the number of iterations, the derived key will be different and it will not work.

Verifying that the recovery is exact

sha256sum tarifas_2026.csv tarifas_2026_recovered.csv

If the two hashes match, the cycle has been perfect. It is the same integrity technique we used in 02-01, applied here as a verification.

The warning about CBC in openssl enc

Note that we have used CBC and not GCM, having said that GCM is the default option. The reason is specific: the enc subcommand of openssl does not support authenticated modes properly. And that has a consequence you need to know about:

openssl enc gives confidentiality, not integrity. If somebody alters the encrypted file along the way, decryption will produce rubbish or a corrupt file, but the command will not warn you that there was deliberate tampering.

How to compensate in practice:

# Encrypt and, separately, authenticate the result with HMAC
openssl enc -aes-256-cbc -pbkdf2 -iter 600000 -in tarifas.csv -out tarifas.enc
openssl dgst -sha256 -hmac "a-different-hmac-key" tarifas.enc > tarifas.enc.hmac

An authentication code is generated for the already-encrypted file, with a key different from the encryption one. The recipient recomputes the HMAC and compares before decrypting. (Exactly what HMAC is and why it adds security over a bare hash is explained in 02-05.)

For real file encryption needs with guaranteed integrity, the sensible thing is to use tools designed for it (age, gpg) or to do it from code, as in the next section.


  1. Hands-on 2: encrypting Rutalia's customer CSV in Python

Now, properly done authenticated encryption. Rutalia exports the customer CSV every night to upload it to S3, and today it uploads it in the clear.

pip install cryptography
#!/usr/bin/env python3
"""
cifrar_clientes.py — Authenticated encryption of Rutalia's customer export.
Uses AES-256-GCM (AEAD): confidentiality + integrity + authenticity.

Usage:
  python3 cifrar_clientes.py encrypt clientes.csv clientes.csv.enc
  python3 cifrar_clientes.py decrypt clientes.csv.enc clientes.csv
The key is taken from the RUTALIA_EXPORT_KEY environment variable (Base64, 32 bytes).
"""

import base64
import os
import sys
from datetime import date

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

KEY_VARIABLE = "RUTALIA_EXPORT_KEY"


def generate_key() -> str:
    """Generate a 256-bit key and return it in Base64 so it can be stored."""
    return base64.b64encode(AESGCM.generate_key(bit_length=256)).decode()


def get_key() -> bytes:
    value = os.environ.get(KEY_VARIABLE)
    if not value:
        raise SystemExit(f"ERROR: the {KEY_VARIABLE} environment variable is missing")
    key = base64.b64decode(value)
    if len(key) != 32:
        raise SystemExit("ERROR: the key must be 32 bytes (256 bits)")
    return key


def encrypt_file(source: str, target: str) -> None:
    aesgcm = AESGCM(get_key())

    # A UNIQUE 96-bit nonce for this encryption. It is never reused.
    nonce = os.urandom(12)

    # Associated data: travels IN THE CLEAR but stays AUTHENTICATED.
    # Nobody can change the date or the source without invalidating the tag.
    aad = f"rutalia|customer_export|{date.today().isoformat()}".encode()

    with open(source, "rb") as f:
        plaintext = f.read()

    ciphertext = aesgcm.encrypt(nonce, plaintext, aad)

    # Format of the output file:
    #   [2 bytes: aad length][aad][12 bytes: nonce][ciphertext + tag]
    with open(target, "wb") as f:
        f.write(len(aad).to_bytes(2, "big"))
        f.write(aad)
        f.write(nonce)
        f.write(ciphertext)

    print(f"OK  {source} ({len(plaintext)} B) -> {target} ({len(ciphertext)} B)")
    print(f"    authenticated context: {aad.decode()}")


def decrypt_file(source: str, target: str) -> None:
    aesgcm = AESGCM(get_key())

    with open(source, "rb") as f:
        data = f.read()

    aad_length = int.from_bytes(data[:2], "big")
    aad = data[2:2 + aad_length]
    nonce = data[2 + aad_length:14 + aad_length]
    ciphertext = data[14 + aad_length:]

    try:
        plaintext = aesgcm.decrypt(nonce, ciphertext, aad)
    except Exception:
        raise SystemExit(
            "ERROR: the integrity check has FAILED.\n"
            "The file has been altered or the key is wrong. "
            "Nothing is decrypted."
        )

    with open(target, "wb") as f:
        f.write(plaintext)
    print(f"OK  {source} -> {target} ({len(plaintext)} B), integrity verified")
    print(f"    authenticated context: {aad.decode()}")


if __name__ == "__main__":
    if len(sys.argv) == 2 and sys.argv[1] == "generate-key":
        print(generate_key())
    elif len(sys.argv) == 4 and sys.argv[1] == "encrypt":
        encrypt_file(sys.argv[2], sys.argv[3])
    elif len(sys.argv) == 4 and sys.argv[1] == "decrypt":
        decrypt_file(sys.argv[2], sys.argv[3])
    else:
        raise SystemExit(__doc__)

An explanation of the decisions

  • AESGCM implements AES in GCM mode, that is, authenticated encryption. A single call gives confidentiality and integrity. The package is called hazmat (hazardous materials) precisely to remind you that these are low-level primitives to be handled with care.
  • AESGCM.generate_key(bit_length=256) generates the key with the system's secure generator. Never derive a key from a hand-typed string without going through a KDF.
  • os.urandom(12) generates the nonce. It is the critical point of the program: if this value were repeated with the same key, security would be destroyed. That is why it is generated randomly on each run and never fixed or cached.
  • The aad (associated data) is the most interesting part from a teaching point of view. rutalia|customer_export|2026-09-22 travels in the clear inside the file — it can be read without the key — but it is authenticated: if somebody changes the date or the export type, decryption fails. It serves to tie the ciphertext to its context and prevent an encrypted file being reused by passing it off as another.
  • The output format is designed to be readable: first the length of the aad (2 bytes), then the aad, then the nonce (a fixed 12 bytes) and then the rest. Without an explicit format, the recipient would not know where each part begins. Writing the lengths explicitly is what every real cryptographic format does.
  • The authentication tag (16 bytes) is appended to the end of the ciphertext by the library; that is why the encrypted file is 16 bytes larger than the original.
  • decrypt raises an exception if the tag does not match, and the program writes nothing. This behaviour is fundamental: faced with tampering, the system must fail, not return partially correct data. Note too that the error message does not distinguish between "wrong key" and "altered file": giving that information would help an attacker.

Usage

# 1. Generate the key ONCE and store it in the secrets manager
$ python3 cifrar_clientes.py generate-key
k9Xm2pQ7vR4tY6uI8oP0aS3dF5gH7jK1lZ2xC4vB6n8=

# 2. Load it as an environment variable (in production, from the KMS)
$ export RUTALIA_EXPORT_KEY='k9Xm2pQ7vR4tY6uI8oP0aS3dF5gH7jK1lZ2xC4vB6n8='

# 3. Encrypt the nightly export
$ python3 cifrar_clientes.py encrypt clientes.csv clientes.csv.enc
OK  clientes.csv (128443 B) -> clientes.csv.enc (128459 B)
    authenticated context: rutalia|customer_export|2026-09-22

# 4. Simulate tampering with the encrypted file
$ printf '\x41' | dd of=clientes.csv.enc bs=1 seek=200 conv=notrunc 2>/dev/null

# 5. Try to decrypt
$ python3 cifrar_clientes.py decrypt clientes.csv.enc recovered.csv
ERROR: the integrity check has FAILED.
The file has been altered or the key is wrong. Nothing is decrypted.

Steps 4-5 are the demonstration everybody should see once in their life: we have changed a single byte and the system has detected it. With CBC and no MAC, that same change would have produced a file with one corrupted block and the program would have handed it over without a care.


  1. Hands-on 3: an RSA key pair at the console

To close, let us get hands-on with the asymmetry between public and private keys.

Generating the pair

# 1. Generate the 2048-bit RSA private key
openssl genrsa -out rutalia_privada.pem 2048

# 2. Protect the file: ONLY the owner can read it
chmod 600 rutalia_privada.pem

# 3. Extract the PUBLIC key from the private one
openssl rsa -in rutalia_privada.pem -pubout -out rutalia_publica.pem

# 4. View the key's details
openssl rsa -in rutalia_privada.pem -noout -text | head -5
  • genrsa ... 2048: 2048 bits is the acceptable minimum today. For long-term needs, 3072 or 4096; for a new system, consider elliptic curves instead (openssl ecparam -genkey -name prime256v1).
  • chmod 600 is as important as the command itself. A private key readable by other users of the system is not private. It is always worth checking.
  • -pubout derives the public key from the private one. Note the asymmetry: from the private key you obtain the public one trivially; the other way round is infeasible. That is exactly the property everything rests on.
  • The private .pem file contains, as well as the private key's data, the public key's. That is why you never send the private key file "so they can verify": you send the public one.

Encrypting with the public key, decrypting with the private one

# A short message: a session key, not a large file
echo -n "session-key-9f3a2b7c" > secreto.txt

# 5. Encrypt with the PUBLIC key (anybody can do this)
openssl pkeyutl -encrypt \
    -pubin -inkey rutalia_publica.pem \
    -pkeyopt rsa_padding_mode:oaep \
    -pkeyopt rsa_oaep_md:sha256 \
    -in secreto.txt -out secreto.enc

# 6. Decrypt with the PRIVATE key (only its owner)
openssl pkeyutl -decrypt \
    -inkey rutalia_privada.pem \
    -pkeyopt rsa_padding_mode:oaep \
    -pkeyopt rsa_oaep_md:sha256 \
    -in secreto.enc -out recuperado.txt

cat recuperado.txt        # session-key-9f3a2b7c

Points that explain why the command is so long:

  • pkeyutl replaces the old rsautl, which is obsolete. If you find rsautl in documentation or in old scripts, that is a sign the material is out of date.
  • -pubin indicates that the key file contains a public key. Without that option, openssl would expect a private one.
  • -pkeyopt rsa_padding_mode:oaep is the option that cannot be omitted. Padding adds structured randomness before encrypting, and without it RSA is deterministic and insecure: the same message would always produce the same ciphertext, and well-known practical attacks exist. Raw RSA, without proper padding, is broken. OAEP is the recommended padding scheme for encryption.
  • The message must be shorter than the key: with RSA-2048 and OAEP-SHA256, the maximum is around 190 bytes. If you try to encrypt a larger file, openssl will fail. That limitation is precisely the reason for the hybrid encryption in section 8: which is why the example encrypts a session key, not a document.

The experiment you should run

# Encrypt the SAME content twice with the SAME public key
openssl pkeyutl -encrypt -pubin -inkey rutalia_publica.pem \
    -pkeyopt rsa_padding_mode:oaep -in secreto.txt -out c1.enc
openssl pkeyutl -encrypt -pubin -inkey rutalia_publica.pem \
    -pkeyopt rsa_padding_mode:oaep -in secreto.txt -out c2.enc

sha256sum c1.enc c2.enc

The two hashes are different. Same message, same key, different results: that is OAEP padding doing its job, exactly like the nonce in AES-GCM and the salt in bcrypt. Randomising the input is a pattern that recurs throughout modern cryptography, and where it is missing — ECB, RSA without padding, hashing without a salt — is where the vulnerabilities appear.


Comparison table: symmetric versus asymmetric

Aspect Symmetric Asymmetric
Keys One, shared Two: public and private
Usual algorithms AES, ChaCha20 RSA, ECDSA, Ed25519, ECDH
Typical key size 128 or 256 bits 2048-4096 bits (RSA), 256 bits (ECC)
Speed Very fast (GB/s) Slow (2-3 orders of magnitude less)
Message size Unlimited Limited (about 190 B with RSA-2048)
Key distribution A hard problem Solved: the public key is published
Number of keys for N parties N(N-1)/2 2N
Does it give non-repudiation? No Yes (through signing)
Main use Encrypting data in bulk Key exchange, signing, authentication
In practice They are combined: hybrid encryption

A note on the quantum threat. A sufficiently large quantum computer would break RSA and elliptic-curve cryptography, while symmetric cryptography would only be weakened (AES-256 would remain sound). The analysis of that threat, the realistic timescales, the "harvest now, decrypt later" problem and the post-quantum algorithms already standardised are covered in Quantum Computing and Post-Quantum Cryptography.


Common Mistakes and Tips

Mistake 1: believing that encrypting solves access control. Encrypting the database stops neither an IDOR nor an insider: the application decrypts for whoever asks. Tip: encrypt to protect yourself against theft of the media and against provider access; for everything else, authorisation.

Mistake 2: choosing the algorithm and neglecting the mode. AES-256-ECB is worse than AES-128-GCM. Tip: the important decision is the mode, and the answer is GCM or ChaCha20-Poly1305.

Mistake 3: storing the key next to the encrypted data. Tip: environment variables, a secrets manager or a KMS; and if the key has ever passed through the repository, rotate it.

Mistake 4: using random instead of secrets. Tip: secrets and os.urandom for anything that is a key, nonce, token or code; random only for simulations.

Mistake 5: reusing nonces. Tip: generate them with os.urandom on every operation and do not store them "to reuse later".

Mistake 6: encrypting without authenticating. Tip: if your code uses CBC, look for the MAC; if there is none, migrate to AEAD.

Mistake 7: encrypting passwords instead of deriving them. If your system can recover the password, it is badly designed. Tip: passwords with bcrypt or Argon2 (02-03); encryption for data you need to get back.

Mistake 8: having no key recovery plan. Losing the key is equivalent to destroying the data. Tip: back the key up, held separately, with a tested recovery procedure.

Mistake 9: falling for the marketing. "Military-grade encryption" means nothing technically. Tip: there are four useful questions to ask a supplier: which algorithm and which mode, how the keys are generated, where they are held and who can access them, and how they are rotated. The third is the one that separates serious suppliers from the rest.

A final tip: your role is not to design cryptography, it is not to spoil the cryptography that already exists. In practice that boils down to five decisions: use AES-256-GCM or ChaCha20-Poly1305, generate keys and nonces with the system's secure generator, never reuse a nonce, keep keys out of the code, and plan how to rotate them and how to recover them. If you get those five right, you will be ahead of most of the applications you will audit in your career.


Exercises

Exercise 1: auditing MiRutalia's cryptographic code

Marta Ruiz has written this module to encrypt customers' banking details before storing them. Laura asks you to review it before it reaches production.

import base64
import hashlib
import random
from Crypto.Cipher import AES

MASTER_KEY = "MiRutalia2024Secret"

def _key():
    return hashlib.md5(MASTER_KEY.encode()).digest()

def encrypt_iban(iban: str) -> str:
    cipher = AES.new(_key(), AES.MODE_ECB)
    padding = 16 - (len(iban) % 16)
    data = iban + chr(padding) * padding
    return base64.b64encode(cipher.encrypt(data.encode())).decode()

def decrypt_iban(ciphertext: str) -> str:
    cipher = AES.new(_key(), AES.MODE_ECB)
    data = cipher.decrypt(base64.b64decode(ciphertext)).decode()
    return data[:-ord(data[-1])]

def generate_recovery_token() -> str:
    return "".join(random.choice("0123456789abcdef") for _ in range(16))
  1. Identify all the cryptographic problems, ordered by severity.
  2. For each one, explain the specific attack it allows.
  3. Rewrite the module correctly.

Exercise 2: choosing the right cryptographic scheme

For each Rutalia situation, state: which type of cryptography you would use (symmetric, asymmetric, hybrid, hash or KDF), which specific algorithm and mode, where you would hold the key, and which property of the CIA triad you are protecting.

  1. The nightly customer export uploaded to AWS S3.
  2. The passwords of the 400 customers of the MiRutalia portal.
  3. The laptops of the 25 head office employees.
  4. The communication between the cold store IoT probes and the central system.
  5. A contract Rutalia sends to a customer, who must not be able to deny having received and accepted it.
  6. Verifying that the ERP update package the vendor sends is genuine.
  7. A file of payroll data that Laura emails to the accountancy firm.

Exercise 3: analysing a nonce reuse incident

Rutalia's IoT probe system encrypts each reading with AES-256-GCM. The probe firmware, developed by the manufacturer, generates the nonce like this:

// Probe firmware — nonce generation
uint8_t nonce[12];
uint32_t counter = 0;           // initialised to 0 at boot

void build_nonce() {
    memset(nonce, 0, 12);
    memcpy(nonce, &probe_id, 4);     // 4 bytes: probe identifier
    memcpy(nonce + 4, &counter, 4);  // 4 bytes: incremental counter
    counter++;                       // the last 4 bytes stay at zero
}

All the probes in one warehouse share the encryption key.

  1. Identify the problem and explain exactly when it occurs.
  2. What can an attacker who captures the encrypted traffic do? Distinguish between what they can read and what they can forge.
  3. What physical consequence could it have for Rutalia's business?
  4. Propose three solutions: one immediate and applicable without touching the firmware, and two fundamental ones.

Solutions

Solution to Exercise 1

1 and 2. Problems, by severity

# Problem Attack it allows
1 AES.MODE_ECB Identical IBANs produce identical ciphertexts. An attacker with the table identifies which customers share a bank account and, with a single known plaintext/ciphertext pair, labels every occurrence. Moreover, since Spanish IBANs have a fixed structure, inferences can be made block by block
2 No authentication (AEAD) Nobody detects alteration of the ciphertext. Combined with ECB, an attacker with database access can swap blocks between records to assign one customer another's IBAN, or their own. It is hypothesis H2 executed from the inside
3 hashlib.md5 to derive the key MD5 is fast and broken. The key is derived from a password with a fast function, with no salt and no work factor: a dictionary attack on the master password is trivial. Besides, MD5 gives 16 bytes → the key ends up being AES-128, not 256
4 MASTER_KEY embedded in the code Anybody with access to the repository has the key, and it stays in the Git history forever. It cannot be rotated without deploying
5 random.choice for the recovery token A predictable generator: by observing a few tokens you can reconstruct the state and predict the next ones. It allows other people's accounts to be taken over through the recovery flow (remember 02-03: recovery is the back door)
6 A token of only 16 hexadecimal characters (64 bits) A reduced search space; added to point 5, it is a serious failing
7 Hand-rolled padding with no validation A home-made implementation of PKCS#7 padding, without checking its validity on decryption, has historically been the origin of padding oracle attacks
8 No error handling on decryption decrypt_iban can raise unhandled exceptions whose message reveals information to the attacker

3. The rewritten module

"""cripto.py — Encryption of banking data for MiRutalia. Corrected version."""
import base64
import os
import secrets

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

# 1. The key comes from the environment or the KMS. NEVER from the code.
_KEY_B64 = os.environ.get("MIRUTALIA_DATA_KEY")
if not _KEY_B64:
    raise RuntimeError("MIRUTALIA_DATA_KEY missing: the application will not start")

_KEY = base64.b64decode(_KEY_B64)
if len(_KEY) != 32:
    raise RuntimeError("The key must be 32 bytes (AES-256)")

_aesgcm = AESGCM(_KEY)


def encrypt_iban(iban: str, customer_id: int) -> str:
    """Encrypt an IBAN with AES-256-GCM, tying it to its customer via the AAD."""
    nonce = os.urandom(12)                        # 2. A unique nonce per operation
    aad = f"iban|customer:{customer_id}".encode() # 3. Tied to the customer
    ciphertext = _aesgcm.encrypt(nonce, iban.encode("utf-8"), aad)
    # Stored as nonce + ciphertext (which already includes the 16-byte tag)
    return base64.b64encode(nonce + ciphertext).decode()


def decrypt_iban(stored: str, customer_id: int) -> str:
    """Decrypt and verify. Raises ValueError if there was tampering."""
    data = base64.b64decode(stored)
    nonce, ciphertext = data[:12], data[12:]
    aad = f"iban|customer:{customer_id}".encode()
    try:
        return _aesgcm.decrypt(nonce, ciphertext, aad).decode("utf-8")
    except Exception:
        # 4. A generic message: the exact cause is not revealed
        raise ValueError("Banking details could not be verified")


def generate_recovery_token() -> str:
    """A 256-bit token from a cryptographically secure generator."""
    return secrets.token_urlsafe(32)              # 5. secrets, not random

The five key corrections: GCM instead of ECB (real confidentiality + integrity), the key from the environment instead of embedded, a unique nonce per operation, an AAD tying the IBAN to its customer — so that copying one customer's encrypted record to another makes decryption fail, closing the swapping attack — and secrets for the token. The hand-rolled padding is also removed: GCM does not need it.

A final note for Marta: when deploying this, all existing data has to be re-encrypted and, given that the previous key was in the repository, every IBAN encrypted up to today must be considered compromised.

Solution to Exercise 2

# Case Type Algorithm Key custody CIA property
1 Export to S3 Symmetric (or hybrid with the KMS) AES-256-GCM The AWS KMS, with permissions separate from the bucket's Confidentiality + integrity
2 Customer passwords KDF, not encryption Argon2id (or bcrypt cost ≥12) There is no key: a per-user salt is used Confidentiality (the system must not be able to recover them)
3 Laptops Symmetric (full disk encryption) AES-256-XTS (the standard mode for disks) The machine's TPM + a recovery key held by IT Confidentiality against physical theft
4 IoT probes → central system Symmetric with AEAD, a unique key per probe ChaCha20-Poly1305 (better without AES acceleration on modest hardware) Provisioned at commissioning; rotatable Integrity and authenticity above all, and confidentiality
5 Contract with non-repudiation Asymmetric: digital signature ECDSA P-256 or RSA-2048 with SHA-256, plus a timestamp The signer's private key; a recognised certificate Non-repudiation, authenticity, integrity
6 ERP update Asymmetric: signature verification The vendor's signature verified with their public key Rutalia only holds the vendor's public key Authenticity and integrity (a defence against H5)
7 Payroll to the accountancy firm Hybrid AES-256-GCM for the file + the key protected with the firm's public key Each party keeps its own private key Confidentiality + integrity

Observations worth drawing out:

  • Case 2 is a deliberate trap: passwords are not encrypted. If they could be decrypted, the system could recover them, and that is precisely what it must not be able to do (02-03).
  • Case 4 is the one most people get wrong: instinct says "confidentiality", but nobody is interested in stealing a temperature reading. What is critical is that nobody should be able to forge one. The dominant property is authenticity, and that is why AEAD is mandatory rather than optional.
  • Cases 5 and 6 are the only ones that require asymmetric cryptography, and for the same reason: many people need to be able to verify what only one can produce.
  • Case 3 gives the greatest practical return: it is the scenario that genuinely happens — a laptop left on a train — and it is solved by switching on a feature that already comes with the operating system.

Solution to Exercise 3

1. The problem and when it occurs.

The nonce is built as [probe_id:4][counter:4][zeros:4], and the counter resets to 0 every time the probe boots. As the key is shared by every probe in the warehouse and does not change on reboot, each restart makes the probe use exactly the same nonces it has already used: id|0|0, id|1|0, id|2|0…

The exact moment it happens: on every power cut, every maintenance reboot, every battery change, every restart triggered by the hardware watchdog. In an industrial cold store, that happens regularly. The failure is not hypothetical: it is weekly.

There is a second latent problem: the last 4 bytes are always zero, which reduces the effective nonce space; and the 32-bit counter would eventually overflow and reset by itself in a long-lived probe.

2. What the attacker can do.

What they can read: when two messages are encrypted with the same (key, nonce) pair in GCM — which internally works in counter mode — the attacker obtains, by XOR-ing the two ciphertexts, the XOR of the two plaintexts. Since temperature readings have a very rigid and predictable format ({"sonda":"ZGZ-03","temp":-18.2,"ts":...}), knowing or guessing one of the two messages reveals the other completely. With many repeated pairs, the whole stream is reconstructed.

What they can forge — and this is the serious part: nonce reuse in GCM allows the authentication key GCM uses to compute its tags to be recovered. With it, the attacker can generate fake messages with valid tags. In other words, they do not just read: they write. They can inject temperature readings that the central system will accept as legitimate and correctly authenticated.

The difference from other cryptographic failings is qualitative: in GCM, reusing a nonce does not weaken security, it annuls it, both in confidentiality and in authenticity.

3. The physical consequence for the business.

An attacker — or an employee with the knowledge and a motive — could keep the central system reporting -18 °C while the actual cold store is at -4 °C. Nobody would receive any alarm, because the fake messages would pass the authenticity check.

The result: a whole truckload of chilled produce has its cold chain broken without a single alert being raised. The consequences chain together on their own — loss of goods, breach of contract with the customer, a possible food safety problem and legal liability, and reputational damage in Rutalia's most profitable business segment. It is the perfect demonstration of something we saw in 02-01: in cyber-physical systems, an integrity failure does not destroy information, it destroys goods.

It is worth noting that the property compromised is integrity and authenticity, not confidentiality. Nobody cares about spying on a temperature; the damage lies in being able to lie about it.

4. Solutions.

Immediate, without touching the firmware:

Detection at the central system. Record the nonces received per probe and reject and alert on any repetition within a reasonable window. It is a table of seen nonces and a check. It does not fix the cryptography — the material is already exposed — but it turns a silent attack into an immediate alert, and it also detects every probe restart. As a complement: alert on the absence of readings (what we identified in 02-01 as the key control for A006) and cross-check against an independent source, even if that is a manual temperature check once per shift, which is a perfectly valid analogue integrity control.

Fundamental, solution 1: a nonce with a random component and a persistent counter. Fix the firmware so that (a) the counter is stored in non-volatile memory and never goes backwards after a restart, and (b) a random component generated at boot is placed in the bytes that today stay at zero. The essential point is that the nonce must never be able to repeat for the same key, not even after a power cut.

Fundamental, solution 2: one key per probe, with rotation. Give each probe its own encryption key, provisioned individually. That way, even if one probe repeats nonces, the impact is limited to that probe and does not compromise every one in the warehouse. Added to periodic key rotation, the time window is bounded too. This applies the same principle of compartmentalisation we used with accounts in 02-02: one key per purpose, so that compromising one does not compromise everything.

And a process lesson, beyond the technical one: this flaw was introduced by the probe manufacturer, not by Rutalia. It is pure supply chain risk, and it points to two necessary practices: requiring device suppliers to provide evidence of cryptographic review before buying, and planning how the firmware of a device installed inside a cold store gets updated. Both are covered in The Internet of Things (IoT) and Security and Supplier and Supply Chain Security.


Conclusion

You have put cryptography in its exact place: it protects data beyond the reach of your access controls — in transit over a network you do not control, at rest on a disk that can be stolen, at a provider that is not yours — and it does not replace authorisation, it does not protect against the insider or against the IDOR, and it does not fix a badly stored key. You have learned Kerckhoffs's principle and its practical corollary: good algorithms are public, only the key is secret, and a supplier boasting of a proprietary algorithm is admitting that nobody has reviewed it.

You have understood symmetric encryption and, above all, that the decision that matters most is not the key size but the mode of operation: AES-256 in ECB preserves the patterns in your data and AES-128 in GCM does not, which makes "AES-256-ECB" a worse option than "AES-128-GCM" however good it sounds. You have seen why authenticated encryption (AEAD) stopped being a luxury — without it, an attacker alters the ciphertext without anyone detecting it — and you have internalised the rule that governs its use: one key, one nonce, one message, because repeating a nonce in GCM does not weaken security, it destroys it. You have understood the two keys of asymmetric cryptography and their two opposite uses — you encrypt with someone else's public key, you sign with your own private key — you have worked through a Diffie-Hellman exchange by hand, confirming that the shared secret never travels over the channel, and you have seen why in practice every real system uses hybrid encryption: the speed of symmetric with the ease of distribution of asymmetric. You have gone through the key life cycle, which is where it is really won or lost, and the catalogue of classic mistakes: inventing algorithms, using ECB, embedding keys in the code, random instead of secrets, reusing nonces and confusing encryption with hashing or with encoding. And you have practised it: encrypting with openssl, building an authenticated cipher in Python that detects the change of a single byte, and confirming with your own hands that two RSA encryptions of the same message are different thanks to padding.

One piece remains without which none of this quite fits together. We have used hashes without defining them, we have mentioned HMAC three times promising to explain it, and we have taken for granted something that is not remotely trivial: that when you encrypt with "Marta's public key", that key really is Marta's and not an impostor's. Diffie-Hellman, without authentication, is vulnerable to whoever positions themselves in the middle; asymmetric encryption is of no use if you cannot trust the public key you have been given. Solving that problem — how trust is distributed at internet scale — is what public key infrastructure does. In Hashes, Digital Signatures and Certificates (PKI), the lesson that closes this module, you will see exactly what a hash function is and why MD5 and SHA-1 are broken, what HMAC adds over a plain hash, how a digital signature works and what it really guarantees, what an X.509 certificate contains field by field, how it is revoked and what happens when one expires on a Saturday night — as nearly happened to the MiRutalia portal.

© Copyright 2026. All rights reserved