SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 11

Cybersecurity Fundamentals · Lesson 11 of 90 · 13 min

Symmetric encryption: AES, ChaCha20 and modes

symmetric keyblock cipherstream cipherAESAES-128/192/256roundsDES and 3DES (legacy)ChaCha20modes of operationECB (and the penguin problem)CBCCTRinitialisation vector (IV)nonce

These are the notes for Cybersecurity Fundamentals (defensive), episode 11. Last time we built the foundations of cryptography: plaintext (the readable message), ciphertext (the scrambled version), keys, keyspace, randomness, and the perfect but impractical one-time pad. Today you invent the encryption that protects almost everything you do online. You'll invent each idea from a real-life problem: the symmetric key, block ciphers and AES (with its rounds and AES-128/192/256), why DES and 3DES are retired, modes of operation and the ECB penguin, padding with PKCS#7, CBC and the IV, CTR, keystreams and nonces, stream ciphers and ChaCha20, and finally the key distribution problem. The big lesson: the way you use a cipher matters as much as the cipher itself. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Riya, Aman, Ravi, Anu and the payments are made up. Every code sample runs as-is on your own machine with Python 3.13 and the cryptography package (pip install cryptography, version 50.0.1 here); outputs are real. Demos that use random keys, IVs or nonces print different values every run, so your hex will not match ours; the pattern (equal or different) will.

The problems you'll solve

Problem Idea it teaches
The one-time pad needs a key as long as the data Symmetric key: one short shared secret, reused
Scramble data with that short key Block cipher, AES, rounds, AES-128/192/256
A 14-byte message crashes Block ciphers only eat whole 16-byte blocks; key sizes
Old ciphers with short keys DES and 3DES: legacy, decrypt-only
Long messages: chop them into blocks? Mode of operation, ECB, the ECB penguin
Messages that don't fill a block; repeats that leak Padding (PKCS#7), CBC, XOR, the IV
Any length, no padding CTR, counter, keystream, nonce, stream cipher
A phone without AES hardware ChaCha20
How do Riya and Aman share the key at all? The key distribution problem

Problem 1: one short shared key (symmetric key)

The one-time pad from episode 10 is unbreakable, but its key must be as long as all the data you ever send, and never reused. Riya and Aman want something practical: one short key, used again and again. Think of a flat with two copies of the same house key:

At home In encryption Meaning
Two copies of one key Symmetric key The same secret key encrypts and decrypts; both sides hold a copy
Lock and unlock every day with it Reusable One 128-bit key can protect gigabytes of data
Lose it, and anyone gets in Keep it secret Whoever has the key can decrypt everything

Quick units: a bit is a single 0 or 1; a byte is 8 bits (one character like A, or a number from 0 to 255). So a 128-bit key is 16 bytes.

Since the key is the only secret, we need a cipher strong enough that the key is the only way in. Let's build it one block at a time.

Problem 2: a scrambling machine (block cipher and AES)

A block cipher is a scrambling machine: it takes a fixed-size block of plaintext (a chunk of bytes) plus a key, and outputs a ciphertext block of the same size. Change the key and you get a totally different scramble; with the key, you can run it backwards to decrypt.

16 bytes plaintext  ->  [ AES + key ]  ->  16 bytes ciphertext

The block cipher everyone uses is AES, the Advanced Encryption Standard:

  • Its blocks are 128 bits = 16 bytes.
  • It was designed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen, under the name Rijndael. It was announced as the US standard FIPS 197 on 26 Nov 2001, effective 26 May 2002.
  • Inside, AES works in rounds: each round substitutes bytes, shuffles and mixes them, and adds part of the key, so every output bit depends on every input bit. A 128-bit key gets 10 rounds, 192 bits 12, and 256 bits 14. That's AES-128, AES-192 and AES-256: the number is the key length in bits (the block is always 128 bits).
  • There is no known practical attack on correctly implemented AES. The weak spot is how people use it, which is the rest of this episode.

Demo 1: one real AES block

We use Python's cryptography library, a widely used package that provides real, tested encryption (never write your own AES). Cipher(algorithm, mode) builds a cipher; .encryptor() gives an object whose .update() encrypts and .finalize() finishes. (modes.ECB() is explained in Problem 3; for one block it simply means "just run AES".)

from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key = bytes(range(16))         # 16-byte key: AES-128
aes = Cipher(algorithms.AES(key), modes.ECB()).encryptor()

block = b"PAY RAVI RS 500."        # exactly 16 bytes
print(len(block), "bytes in ->", aes.update(block).hex())

Output:

16 bytes in -> b8f9bb9b67603b5e1bf626c8b0bf10e7

Sixteen bytes in, sixteen scrambled bytes out (.hex() shows each byte as two hex digits, so 32 characters). bytes(range(16)) is the fixed key 00 01 02 ... 0f, used here only so you get the same output as us; real keys must be random.

Demo 2: the obvious attempt fails (a 14-byte message)

Riya's next message is shorter: "PAY RAVI RS 50", only 14 bytes.

from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key = bytes(range(16))
aes = Cipher(algorithms.AES(key), modes.ECB()).encryptor()

msg = b"PAY RAVI RS 50"         # only 14 bytes
print(aes.update(msg) + aes.finalize())

Output (file path shortened):

Traceback (most recent call last):
  File "short.py", line 8, in <module>
    print(aes.update(msg) + aes.finalize())
                            ~~~~~~~~~~~~^^
ValueError: The length of the provided data is not a multiple of the block length.

A ValueError is Python's error for "right type, wrong value". Why: a block cipher only eats whole blocks. 14 bytes is not a multiple of 16, so finalize() refuses. Hold that thought; Problem 4 fixes it.

Demo 3: only real AES key sizes

import os
from cryptography.hazmat.primitives.ciphers import algorithms

for n in (16, 24, 32, 5):                 # bytes
    try:
        algorithms.AES(os.urandom(n))
        print(f"{n*8:3}-bit key: OK")
    except ValueError as e:
        print(f"{n*8:3}-bit key: {e}")

Output:

128-bit key: OK
192-bit key: OK
256-bit key: OK
 40-bit key: Invalid key size (40) for AES.

os.urandom(n) returns n random bytes from the operating system's CSPRNG (cryptographically secure pseudo-random number generator, episode 10): randomness good enough for keys. AES accepts only 128, 192 or 256-bit keys; the library refuses a weak 40-bit key for you.

Retired ciphers: DES and 3DES

DES (Data Encryption Standard) 3DES (Triple DES)
When Standard FIPS 46, 1977 A stopgap after DES
Block 64 bits 64 bits (small)
Key 56 bits effective DES run three times with different keys
Rounds 16 three DES passes
Status 1998: a machine called Deep Crack found a DES key in 56 hours NIST (the US National Institute of Standards and Technology) disallowed it for encryption after 31 Dec 2023; allowed only to decrypt legacy data

DES's key is far too short to resist brute force (trying every key). 3DES is slow and has small 64-bit blocks. Use AES. If you meet 3DES in an old system, it's for reading old data only, never for encrypting anything new.

Problem 3: long messages (ECB and the penguin)

Real data is longer than 16 bytes. Here's a 64-byte payment file: four 16-byte lines. The obvious fix: chop it into blocks and encrypt each one separately with the same key.

A way of using a block cipher on data longer than one block is called a mode of operation. This simplest one is ECB, Electronic Codebook: each block is encrypted on its own, like looking each one up in a fixed codebook. But a block cipher is a fixed scramble: the same plaintext block with the same key always gives the same ciphertext block.

Demo 4: three identical payments

from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key = bytes(range(16))
aes = Cipher(algorithms.AES(key), modes.ECB()).encryptor()

msg = b"PAY RAVI RS 500." * 3 + b"PAY ANU RS 9000."
ct = aes.update(msg)
for i in range(0, len(ct), 16):          # one line per block
    print(f"block {i//16}: {ct[i:i+16].hex()}")

Output:

block 0: b8f9bb9b67603b5e1bf626c8b0bf10e7
block 1: b8f9bb9b67603b5e1bf626c8b0bf10e7
block 2: b8f9bb9b67603b5e1bf626c8b0bf10e7
block 3: 18ac4947c94e001a024f7e740f97fb40

Blocks 0, 1 and 2 are identical (and equal Demo 1's output). An eavesdropper can't read them, but he learns that three payments were exactly the same. Why: ECB has no memory between blocks, so patterns in the plaintext show up in the ciphertext.

Demo 5: the picture shows through

It's worse with pictures. Here is a tiny diamond where every "pixel" is one 16-byte block (16 spaces or 16 #). We encrypt it with AES-ECB and print one letter per encrypted block (the first byte of each block, turned into a letter A to Z).

from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

art = ["   ##   ", "  ####  ", " ###### ", "  ####  ", "   ##   "]
key = bytes(range(16))
aes = Cipher(algorithms.AES(key), modes.ECB()).encryptor()

for row in art:
    # 1 pixel = one 16-byte block
    pixels = b"".join((c * 16).encode() for c in row)
    ct = aes.update(pixels)
    print("".join(chr(65 + b % 26) for b in ct[::16]))

Output:

CCCHHCCC
CCHHHHCC
CHHHHHHC
CCHHHHCC
CCCHHCCC

The diamond is still there, drawn in Hs. The encryption is real AES, and the picture shows straight through. This is the famous ECB penguin: a picture of the Linux penguin encrypted with ECB still shows the penguin. Never use ECB for real data.

Problem 4: padding, CBC and the IV

Part A: messages that don't fill a block (padding, PKCS#7)

First, the crash from Demo 2. The fix is padding: extra bytes added to the end so the message fills the last block. The standard scheme, PKCS#7, says: if you add n bytes, each of them has the value n. The receiver reads the last byte, learns n, and strips exactly n bytes.

Demo 6: PKCS#7 padding

from cryptography.hazmat.primitives import padding

for msg in (b"PAY RAVI RS 50", b"HI", b"PAY RAVI RS 500."):
    p = padding.PKCS7(128).padder()            # 128-bit blocks
    out = p.update(msg) + p.finalize()
    n = len(out) - len(msg)
    tail = f"added {n:2} x {out[-1]:#04x}"
    print(f"{len(msg):2} -> {len(out):2} bytes, {tail}")

Output:

14 -> 16 bytes, added  2 x 0x02
 2 -> 16 bytes, added 14 x 0x0e
16 -> 32 bytes, added 16 x 0x10

Fourteen bytes get two bytes of value 2. Two bytes get fourteen of value 14 (0x0e). A message that already fills a block gets a whole extra block of 16s (0x10), so the last byte is always a padding byte and unpadding is never ambiguous.

Part B: chain the blocks (CBC and the IV)

Padding fixes the crash, but not ECB's leak. Think of a line of dominoes:

Dominoes CBC mode Meaning
The first push, a random flick IV A random 16-byte starting block
Each tile knocks the next Chaining Each block is mixed with the previous ciphertext block
Same tiles, different fall if the push differs No repeats The same block gives new ciphertext

XOR (exclusive or, written ^ in Python) combines two bits: the result is 1 when they differ, 0 when they're the same. XOR-ing the same value twice cancels out, which is why it's used everywhere in cryptography.

CBC, Cipher Block Chaining: before encrypting each plaintext block, XOR it with the previous ciphertext block. Then each block depends on everything before it:

C0 = AES(key, P0 XOR IV)
C1 = AES(key, P1 XOR C0)
C2 = AES(key, P2 XOR C1) ...

The first block has nothing before it, so we start with a random 16-byte block called the IV, initialisation vector. The IV is not secret: it's sent along with the ciphertext. But it must be unpredictable and new for every message. CBC still works on whole blocks, so it needs padding.

Demo 7: the payment file in CBC

import os
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key = bytes(range(16))
iv = os.urandom(16)            # fresh random IV
aes = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()

msg = b"PAY RAVI RS 500." * 3 + b"PAY ANU RS 9000."
ct = aes.update(msg) + aes.finalize()
for i in range(0, len(ct), 16):
    print(f"block {i//16}: {ct[i:i+16].hex()}")

Output (one run; the values change every run because the IV is random):

block 0: fe4bc7065e165409b692b4a38def8a1f
block 1: cfb20fcc00cb895e55195cdaf58fea1a
block 2: 8e2e2eb9732fe7f353e32857c0474099
block 3: 8e443cf00cfaa01580665172fef9e58f

Four completely different blocks. The repeated payments are hidden. (The message is exactly 64 bytes, so this demo skips padding; Practice 4 shows the full pad + CBC + unpad round trip.)

Demo 7b: the diamond in CBC

import os
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

art = ["   ##   ", "  ####  ", " ###### ", "  ####  ", "   ##   "]
key = bytes(range(16))
iv = os.urandom(16)
aes = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()

for row in art:
    # 1 pixel = one 16-byte block
    pixels = b"".join((c * 16).encode() for c in row)
    ct = aes.update(pixels)
    print("".join(chr(65 + b % 26) for b in ct[::16]))

Output (one run; random every time):

ABUBBUTG
QKCFQQJV
SKOKWKOD
MAGAULJY
OXZLFRUR

Noise. The shape is gone. That's what good encryption looks like.

Demo 8: the lazy developer's fixed IV

A voting app sends "VOTE: YES PLEASE" on day 1 and day 2. First with the same IV every time (all zero bytes), then with random IVs. We print the first 8 bytes of each ciphertext.

import os
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key = os.urandom(16)
def cbc(msg, iv):
    e = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
    return (e.update(msg) + e.finalize()).hex()[:16]

vote = b"VOTE: YES PLEASE"
fixed = bytes(16)                    # BUG: the same IV every time
print("fixed IV, day 1: ", cbc(vote, fixed))
print("fixed IV, day 2: ", cbc(vote, fixed))
print("random IV, day 1:", cbc(vote, os.urandom(16)))
print("random IV, day 2:", cbc(vote, os.urandom(16)))

Output (values differ every run; the fixed-IV lines always match each other):

fixed IV, day 1:  be6f05f0dcab58b7
fixed IV, day 2:  be6f05f0dcab58b7
random IV, day 1: 80862ff075f285eb
random IV, day 2: a0b385213a74c313

With a fixed IV, both days give the same ciphertext, so an eavesdropper learns that the same vote was sent twice. With random IVs, they differ. Same lesson as the one-time pad: the starting value must never repeat.

Problem 5: any length, no padding (CTR, nonce, stream cipher)

Padding and chaining work, but there's a neater idea. Remember the one-time pad: XOR the message with a random pad. What if AES could manufacture the pad from a short key?

That's CTR, counter mode:

keystream = AES(key, nonce+0) | AES(key, nonce+1) | AES(key, nonce+2) | ...
ciphertext = plaintext XOR keystream
  • A nonce ("number used once") is a starting value; a counter (0, 1, 2, ...) is added to it for each 16-byte chunk.
  • Encrypting each nonce+counter with AES gives a keystream: a long stream of random-looking bytes.
  • XOR the keystream with the plaintext. Decryption is the same XOR again.

This turns AES into a stream cipher: a cipher that encrypts data byte by byte with a keystream, so there is no padding and any length works. The one rule: the same key and nonce must never be used for two messages. Like the IV, the nonce is not secret and travels with the ciphertext.

Demo 9: the 14-byte message, now fine

import os
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key, nonce = os.urandom(16), os.urandom(16)
aes = algorithms.AES(key)
enc = Cipher(aes, modes.CTR(nonce)).encryptor()

msg = b"PAY RAVI RS 50"                    # 14 bytes, no padding
ct = enc.update(msg) + enc.finalize()
print(len(msg), "bytes ->", len(ct), "bytes:", ct.hex())

dec = Cipher(aes, modes.CTR(nonce)).decryptor()
print(dec.update(ct) + dec.finalize())

Output (the hex differs every run):

14 bytes -> 14 bytes: b92302891d8569de22265db59c70
b'PAY RAVI RS 50'

Fourteen bytes in, fourteen out, no padding, and decryption brings it back.

Demo 10: the lazy developer reuses the nonce

import os
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key, nonce = os.urandom(16), os.urandom(16)
def ctr(msg):             # BUG: same nonce each time
    aes = algorithms.AES(key)
    e = Cipher(aes, modes.CTR(nonce)).encryptor()
    return e.update(msg)

c1 = ctr(b"ATTACK AT DAWN")
c2 = ctr(b"RETREAT AT TEN")
leak = bytes(a ^ b for a, b in zip(c1, c2))
print(bytes(a ^ b for a, b in zip(leak, b"ATTACK AT DAWN")))

Output (the same every run, even though the key is random):

b'RETREAT AT TEN'

Why: the same key and nonce make the same keystream. c1 XOR c2 cancels the keystream and leaves message1 XOR message2; anyone who knows or guesses message 1 recovers message 2. Exactly the reused pad from episode 10. Real AES, totally broken by one repeated nonce.

Problem 6: a phone without AES hardware (ChaCha20)

Many processors have special instructions that run AES very fast. Some cheaper chips don't, and AES in plain software is slower and harder to make resistant to timing tricks. So there is a second modern cipher: ChaCha20.

  • Designed by D. J. Bernstein, a refinement of his earlier cipher Salsa20; standardised in RFC 8439 (June 2018).
  • A stream cipher built only from simple operations: add, rotate and XOR.
  • 256-bit key, 96-bit nonce, 32-bit block counter, keystream made in 64-byte blocks.
  • Its RFC says it is "considerably faster than AES in software-only implementations", about three times faster on platforms without AES hardware, and that nonce uniqueness is the most important security consideration.

Demo 11: ChaCha20 in Python

In the cryptography library, the 16-byte nonce argument holds the 4-byte counter plus the 12-byte (96-bit) nonce.

import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms

key = os.urandom(32)         # 256-bit key
nonce = os.urandom(16)       # counter + nonce
c = Cipher(algorithms.ChaCha20(key, nonce), mode=None)

ct = c.encryptor().update(b"meet at the chai stall")
print("ciphertext:", ct.hex())
print("decrypted: ", c.decryptor().update(ct))

Output (the hex differs every run):

ciphertext: 5d985ba355e6f2c8f64bd7854407faa60e6be8ff0e42
decrypted:  b'meet at the chai stall'

A 22-byte message gives 22 bytes of ciphertext (44 hex digits): a stream cipher again, and it decrypts back. Same rule as CTR: never reuse a nonce with the same key. AES and ChaCha20 are the two ciphers that protect most of your HTTPS traffic (the secure, padlocked version of web browsing) today.

Block ciphers vs stream ciphers

Block cipher (AES) Stream cipher (ChaCha20, or AES-CTR)
Fixed 16-byte blocks Keystream XOR data
Needs a mode: ECB (never), CBC (+ padding + random IV), CTR (acts like a stream), GCM (next episode) Any length, no padding
The mode matters Fast in software; the nonce matters

For both, the one rule you can never break: never reuse a key + nonce (or IV) pair.

Problem 7: how do they share the key? (the key distribution problem)

Riya has a perfect 128-bit AES key, made with the secrets module (Python's CSPRNG interface, episode 10). But Aman needs the same key.

  • If she sends it over the café Wi-Fi, the eavesdropper copies the key and decrypts everything.
  • A website with a million users can't meet each one in advance to share a secret.

That's the key distribution problem: how do two strangers agree on a secret key over a network that anyone can listen to? Symmetric encryption can't solve it on its own. It's solved by asymmetric cryptography (separate public and private keys), in episode 15.

The whole chain

Step Problem You invented
1 A pad as long as the data One short symmetric key
2 Scramble 16 bytes Block cipher, AES, rounds, AES-128/192/256
3 Chop long data into blocks ECB, which leaks the penguin
4 Partial blocks; repeated blocks Padding (PKCS#7), CBC, a random IV
5 Make a pad from a counter CTR, nonce, keystream, stream cipher
6 Fast in software ChaCha20
? Share the key with a stranger The key distribution problem (episode 15)

And a scary question for next time: the man in the middle can't read the message. Can he still change it without anyone noticing? Next episode you'll see he can, and invent the fix.

Common mistakes (and what they print)

Mistake What you see Why it's wrong Fix
AES-ECB (or CBC) on 14 bytes ValueError: The length of the provided data is not a multiple of the block length. Block ciphers eat whole blocks Pad with PKCS#7, or use CTR (or GCM, next episode)
algorithms.AES(os.urandom(5)) ValueError: Invalid key size (40) for AES. AES keys are 128/192/256 bits os.urandom(16) or os.urandom(32)
modes.CBC(os.urandom(8)) ValueError: Invalid IV size (8) for CBC. The CBC IV is one block, 16 bytes os.urandom(16)
modes.CTR(os.urandom(12)) ValueError: Invalid nonce size (12) for CTR. This library wants a full 16-byte counter block os.urandom(16)
algorithms.ChaCha20(os.urandom(16), nonce) ValueError: Invalid key size (128) for ChaCha20. ChaCha20 keys are 256 bits os.urandom(32)
algorithms.ChaCha20(key, os.urandom(12)) ValueError: nonce must be 128-bits (16 bytes) The library's nonce includes the 4-byte counter os.urandom(16)
Unpadding bytes that aren't valid PKCS#7 ValueError: Invalid padding bytes. Wrong key/IV, or the data was damaged or changed Check key and IV; next episode adds integrity checks
modes.ECB() for real data block 0 == block 1 == block 2 Same block gives same ciphertext Never ECB
Fixed IV / reused nonce fixed IV, day 1 == day 2, b'RETREAT AT TEN' Same keystream (or same start) twice A fresh random IV/nonce for every message
bytes(range(16)) as a real key Works, but anyone can guess it Not random os.urandom(16) or secrets.token_bytes(16)
Encrypting new data with 3DES Works in old libraries Disallowed for new encryption after 2023 AES or ChaCha20

Mini project: an ECB detector and a safe file sealer

Part 1: detect ECB. ECB's fingerprint is repeated 16-byte ciphertext blocks. This defensive check counts them, the way a reviewer might scan your own app's stored ciphertext for the ECB mistake.

import os
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

def repeated_blocks(ct, size=16):
    """Count 16-byte ciphertext blocks that appear more than once."""
    blocks = [ct[i:i+size] for i in range(0, len(ct), size)]
    return len(blocks) - len(set(blocks))

def looks_like_ecb(ct):
    return repeated_blocks(ct) > 0

def encrypt(mode, msg, key):
    e = Cipher(algorithms.AES(key), mode).encryptor()
    return e.update(msg) + e.finalize()

key = os.urandom(16)
msg = b"PAY RAVI RS 500." * 3 + b"PAY ANU RS 9000."   # 64 bytes

samples = {
    "ECB":           encrypt(modes.ECB(), msg, key),
    "CBC random IV": encrypt(modes.CBC(os.urandom(16)), msg, key),
    "CTR random nonce": encrypt(modes.CTR(os.urandom(16)), msg, key),
}
for name, ct in samples.items():
    n = repeated_blocks(ct)
    verdict = "LOOKS LIKE ECB - fix it" if looks_like_ecb(ct) else "no repeats"
    print(f"{name:17} {len(ct)} bytes, repeated blocks: {n} -> {verdict}")

Output:

ECB               64 bytes, repeated blocks: 2 -> LOOKS LIKE ECB - fix it
CBC random IV     64 bytes, repeated blocks: 0 -> no repeats
CTR random nonce  64 bytes, repeated blocks: 0 -> no repeats

(Four blocks, three of them equal: 4 - 2 unique = 2 repeats.) No repeats doesn't prove a good mode, since ECB on data without repeated blocks also shows none; but repeats are a strong red flag.

Part 2: seal a file with AES-CTR and a fresh nonce. The safe pattern: a new random nonce for every encryption, stored in front of the ciphertext so the receiver can find it.

import os
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

def seal(key, data):
    nonce = os.urandom(16)                       # fresh every call
    e = Cipher(algorithms.AES(key), modes.CTR(nonce)).encryptor()
    return nonce + e.update(data) + e.finalize()  # nonce travels in front

def unseal(key, blob):
    nonce, ct = blob[:16], blob[16:]
    d = Cipher(algorithms.AES(key), modes.CTR(nonce)).decryptor()
    return d.update(ct) + d.finalize()

key = os.urandom(32)                             # AES-256
with open("diary.txt", "wb") as f:
    f.write(b"Dear diary, the exam went well.")

with open("diary.txt", "rb") as f:
    plain = f.read()
blob1, blob2 = seal(key, plain), seal(key, plain)
with open("diary.txt.enc", "wb") as f:
    f.write(blob1)

print("plaintext bytes: ", len(plain))
print("encrypted bytes: ", len(blob1), "(16-byte nonce + ciphertext)")
print("same file twice, same output?", blob1 == blob2)
with open("diary.txt.enc", "rb") as f:
    print("decrypted:", unseal(key, f.read()))
os.remove("diary.txt"); os.remove("diary.txt.enc")

Output:

plaintext bytes:  31
encrypted bytes:  47 (16-byte nonce + ciphertext)
same file twice, same output? False
decrypted: b'Dear diary, the exam went well.'

Encrypting the same file twice gives different output, because each call uses a new nonce. Two honest limits: the key here lives only in memory (keeping keys safe is its own topic), and nothing stops someone from changing the .enc file. That is exactly next episode's problem.

Practice

1. Homework: add a 5th payment line to the ECB demo. Add another "PAY RAVI RS 500." at the end. What does block 4 look like?

Solution
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key = bytes(range(16))
aes = Cipher(algorithms.AES(key), modes.ECB()).encryptor()

msg = (b"PAY RAVI RS 500." * 3 + b"PAY ANU RS 9000."
       + b"PAY RAVI RS 500.")                 # 5th line
ct = aes.update(msg)
for i in range(0, len(ct), 16):
    print(f"block {i//16}: {ct[i:i+16].hex()}")

Output:

block 0: b8f9bb9b67603b5e1bf626c8b0bf10e7
block 1: b8f9bb9b67603b5e1bf626c8b0bf10e7
block 2: b8f9bb9b67603b5e1bf626c8b0bf10e7
block 3: 18ac4947c94e001a024f7e740f97fb40
block 4: b8f9bb9b67603b5e1bf626c8b0bf10e7

Block 4 equals blocks 0 to 2: the eavesdropper now knows four payments were identical, and which line differs.

2. Homework: draw your own picture in the penguin demo. Replace art with your own 8-wide drawing (here, a Y).

Solution
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

art = ["#      #", " #    # ", "  #  #  ", "   ##   ", "   ##   "]   # a Y
key = bytes(range(16))
aes = Cipher(algorithms.AES(key), modes.ECB()).encryptor()

for row in art:
    pixels = b"".join((c * 16).encode() for c in row)
    ct = aes.update(pixels)
    print("".join(chr(65 + b % 26) for b in ct[::16]))

Output:

HCCCCCCH
CHCCCCHC
CCHCCHCC
CCCHHCCC
CCCHHCCC

The Y shows straight through ECB. Switch to modes.CBC(os.urandom(16)) (and import os) and it turns to noise.

3. Homework: pad 15 bytes with PKCS#7. What is added?

Solution

One byte is missing from the 16-byte block, so PKCS#7 adds one byte of value 1 (0x01).

from cryptography.hazmat.primitives import padding

msg = b"PAY RAVI RS 500"                       # 15 bytes
p = padding.PKCS7(128).padder()
out = p.update(msg) + p.finalize()
print(len(msg), "->", len(out), "bytes")
print(out)

Output:

15 -> 16 bytes
b'PAY RAVI RS 500\x01'

4. Full round trip. Encrypt the 14-byte "PAY RAVI RS 50" with AES-CBC: pad, encrypt, decrypt, unpad.

Solution
import os
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes)

key, iv = os.urandom(16), os.urandom(16)
msg = b"PAY RAVI RS 50"                        # 14 bytes

p = padding.PKCS7(128).padder()
padded = p.update(msg) + p.finalize()
e = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
ct = e.update(padded) + e.finalize()
print("ciphertext:", len(ct), "bytes")

d = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
padded_back = d.update(ct) + d.finalize()
u = padding.PKCS7(128).unpadder()
print("decrypted: ", u.update(padded_back) + u.finalize())

Output:

ciphertext: 16 bytes
decrypted:  b'PAY RAVI RS 50'

The receiver needs the key (secret) and the IV (sent alongside, not secret).

5. Homework: why can't Riya just email Aman the key?

Solution

The email travels over networks other people can read or copy (the café Wi-Fi, mail servers). Anyone who copies the key can decrypt every message encrypted with it, and Riya would never know. And the same trick doesn't scale: a website can't pre-share a secret key with a million strangers. This is the key distribution problem, solved by asymmetric cryptography (episode 15).

6. Pick the mode. For each, say what's wrong or right: (a) ECB for a database of customer records; (b) CBC with iv = bytes(16) on every message; (c) CTR with a counter that restarts at the same nonce after every reboot; (d) ChaCha20 with a fresh random nonce per message.

Solution

(a) Wrong: identical fields give identical ciphertext blocks (the penguin problem). (b) Wrong: a fixed IV reveals when the same message is sent again (Demo 8). (c) Wrong: after a reboot the same key + nonce makes the same keystream, so messages leak exactly like Demo 10. (d) Right: a new keystream every time.

7. AES numbers. How many bytes is an AES-256 key, how big is every AES block, and how many rounds does AES-192 do?

Solution

AES-256 key: 32 bytes. Block: always 16 bytes (128 bits), whatever the key size. AES-192: 12 rounds (AES-128: 10, AES-256: 14).

Quick quiz

One AES key encrypts 1,000 chat messages. Which setup is safe?

# Encrypting 1,000 chat messages with one AES key.
#
# A. ECB mode
# B. CTR mode, nonce = 0 for every message
# C. CBC mode, the same IV for every message
# D. CTR mode, a fresh random nonce per message
Answer

D. CTR, fresh random nonce. ECB leaks patterns. CTR with nonce 0 every time reuses the keystream. CBC with the same IV reveals repeated messages. A fresh random nonce per message keeps every keystream different.

Interview questions

  1. What is symmetric encryption? Encryption where the same secret key encrypts and decrypts, and both sides hold a copy. Examples: AES, ChaCha20.
  2. Block cipher vs stream cipher? A block cipher (AES) transforms fixed-size blocks (16 bytes) and needs a mode for longer data; a stream cipher (ChaCha20, AES-CTR) generates a keystream and XORs it with data of any length, with no padding.
  3. What are AES's block and key sizes? Block 128 bits; keys of 128, 192 or 256 bits, with 10, 12 or 14 rounds.
  4. Why is ECB insecure? Each block is encrypted independently, so identical plaintext blocks give identical ciphertext blocks; patterns (like the ECB penguin) survive encryption.
  5. What is an IV, and must it be secret? An initialisation vector is a random starting block for CBC that makes the same message encrypt differently each time. It isn't secret (it's sent with the ciphertext) but must be unpredictable and new for every message.
  6. What happens if you reuse a nonce in CTR mode or ChaCha20? The same key + nonce produces the same keystream; XOR-ing the two ciphertexts cancels it and leaks the XOR of the plaintexts, so knowing one message reveals the other.
  7. What is PKCS#7 padding? Add n bytes each of value n to fill the last block; a full block gets a whole extra block of 16 bytes of value 16, so unpadding is always unambiguous.
  8. Why are DES and 3DES retired, and when would you choose ChaCha20 over AES? DES has a 56-bit key (Deep Crack found one in 56 hours in 1998); 3DES is slow with 64-bit blocks, and NIST disallowed it for new encryption after 2023. ChaCha20 suits devices without AES hardware, where it's much faster in software.

Glossary

Term Meaning in plain words Example
Plaintext The readable original data b"PAY RAVI RS 500."
Ciphertext The scrambled output of encryption b8f9bb9b...
Bit A single 0 or 1 A 128-bit key has 128 of them
Byte 8 bits; one character or a number 0 to 255 b"A" is one byte
Symmetric key One secret key used both to encrypt and to decrypt, shared by both sides Riya and Aman's AES key
Block A fixed-size chunk of data a block cipher works on 16 bytes for AES
Block cipher A cipher that turns a fixed-size block into a same-size scrambled block using a key AES
Stream cipher A cipher that XORs data with a keystream, byte by byte, any length ChaCha20, AES-CTR
AES Advanced Encryption Standard: the standard block cipher, 128-bit blocks algorithms.AES(key)
Rijndael The original name of the cipher that became AES, by Joan Daemen and Vincent Rijmen AES = Rijndael with 128-bit blocks
AES-128 / 192 / 256 AES with a 128, 192 or 256-bit key os.urandom(32) gives AES-256
Round One pass of substitute, shuffle/mix and add-key inside a cipher, repeated many times AES-128 does 10 rounds
DES Data Encryption Standard (1977): 56-bit key, 64-bit block; long broken Deep Crack, 56 hours (1998)
3DES / Triple DES DES run three times with different keys; legacy, decrypt-only Decrypting an old encrypted archive
NIST US National Institute of Standards and Technology, which publishes crypto standards Retired 3DES for new encryption
FIPS US federal standards documents FIPS 197 = AES, FIPS 46 = DES
Brute force Trying every possible key How DES keys were found
ChaCha20 A fast software stream cipher by D. J. Bernstein: 256-bit key, 96-bit nonce algorithms.ChaCha20(key, nonce)
Salsa20 Bernstein's earlier cipher that ChaCha20 refines ChaCha20's ancestor
RFC 8439 The internet standard document that specifies ChaCha20 June 2018
Mode of operation A recipe for using a block cipher on data longer than one block ECB, CBC, CTR, GCM
ECB Electronic Codebook: each block encrypted alone; leaks patterns modes.ECB(): never for real data
The ECB penguin A picture encrypted with ECB whose shape still shows Our diamond of Hs
Padding Extra bytes added to fill the last block 14 bytes + 2 padding bytes
PKCS#7 Padding rule: add n bytes, each of value n \x02\x02, or 16 × \x10
XOR Bit operation: 1 if the two bits differ, else 0; doing it twice cancels a ^ b in Python
CBC Cipher Block Chaining: XOR each block with the previous ciphertext before encrypting modes.CBC(iv)
Initialisation vector (IV) A random, non-secret starting block for CBC, new every message iv = os.urandom(16)
CTR Counter mode: encrypt nonce+counter to make a keystream, XOR with data modes.CTR(nonce)
Counter The number 0, 1, 2, ... added to the nonce for each chunk Block 3 uses nonce+3
Keystream A long stream of random-looking bytes XORed with the plaintext AES(key, nonce+0), AES(key, nonce+1), ...
Nonce "Number used once": a value that must never repeat with the same key nonce = os.urandom(16)
Nonce reuse Using the same key + nonce twice, which repeats the keystream Demo 10's b'RETREAT AT TEN'
Key distribution problem How two strangers can agree on a secret key over a network anyone can listen to Riya can't safely email the key
Asymmetric cryptography Crypto with a public key and a private key; solves key distribution (episode 15) Pointer only for now
CSPRNG Cryptographically secure pseudo-random number generator: randomness safe for keys (episode 10) secrets, os.urandom
os.urandom Python function returning n random bytes from the OS's CSPRNG os.urandom(16)
secrets module Python's module for security-grade random values secrets.token_bytes(16)
HTTPS The secure, encrypted version of web browsing (pointer only for now) The padlock in your browser
cryptography library A widely used Python package with real, tested encryption pip install cryptography
ValueError Python's error for a value of the right type but wrong content Invalid key size (40) for AES.
GCM A mode that also detects tampering; next episode AES-GCM

Summary

  • A symmetric key is one short shared secret that both encrypts and decrypts; whoever holds it can read everything.
  • AES is the standard block cipher: 16-byte blocks, 128/192/256-bit keys, 10/12/14 rounds. DES and 3DES are legacy: decrypt old data only.
  • A block cipher only eats whole blocks (not a multiple of the block length), so you need a mode of operation.
  • ECB encrypts each block alone, so repeats and pictures leak (the ECB penguin). Never use ECB.
  • PKCS#7 padding fills the last block with n bytes of value n. CBC chains blocks with XOR from a random IV; a fixed IV leaks repeated messages.
  • CTR makes a keystream from a nonce + counter, turning AES into a stream cipher: any length, no padding. ChaCha20 is a fast software stream cipher.
  • The rule you never break: a fresh random IV or nonce for every message, never reused with the same key, and keys from a CSPRNG (os.urandom, secrets).
  • Symmetric encryption can't share its own key: that's the key distribution problem (asymmetric cryptography, episode 15).

Next episode: integrity and authenticated encryption: MAC, HMAC, AES-GCM and ChaCha20-Poly1305, to stop the man in the middle from changing your data.

Sources: Wikipedia, "Advanced Encryption Standard" and "Data Encryption Standard"; NIST CSRC news, "NIST to withdraw SP 800-67 Rev. 2" (2023); RFC 8439 (Nir and Langley, June 2018). Fetched 29 Oct 2026. Code outputs from Python 3.13 with cryptography 50.0.1.