A secret picture you can still see
A developer encrypts every staff photo with AES before saving it. AES is a strong cipher, so the job looks done.
Then somebody opens an encrypted file as a picture, and the outline of each face is still there. The cipher was fine. The way it was used was not.
The one rule
Warning
Every attack in this module is on a toy you write in your own lab. Trying one on a service you do not own needs written permission. In the UK, without it, it can break the Computer Misuse Act 1990.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can show why ECB mode leaks patterns and replace it with AES-GCM.
Key words
| Word | What it means | Example |
|---|---|---|
| Block cipher | a cipher that scrambles 16 bytes at a time | AES |
| Mode | the rule for using a block cipher on longer data | |
| ECB | the mode that scrambles every block alone, the same way | |
| AEAD | encryption that also proves the data was not changed | |
| Nonce | a value used once per message | |
| Tag | the check value an AEAD adds to the ciphertext |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsECB turns equal blocks into equal ciphertext
AES works on 16 bytes at a time. ECB (electronic codebook) mode cuts the data into blocks and encrypts each one alone, with the same key.
So two equal blocks of plaintext always give two equal blocks of ciphertext. Anyone can see which blocks repeat without knowing the key. Pictures, forms and records repeat a lot.
Try it: what repeats in three records
records = [b"id=0412 grade=A ", b"id=0413 grade=C ", b"id=0414 grade=A "]
seen = {}
for record in records:
tail = record[8:]
seen[tail] = seen.get(tail, 0) + 1
for tail, count in seen.items():
print(tail, "appears", count, "times")
# ECB turns equal blocks into equal ciphertext, so these counts leak too.
# Add a fourth record with grade=C. What changes?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsEncrypt a padlock picture with ECB
The lab's Python has the cryptography package. The first Run writes a picture of a padlock, ten blocks wide and eight high. Each block is 16 white or 16 black bytes.
The next writes ecb.py, which encrypts it with AES in ECB mode under a random key. It then prints one letter for each different ciphertext block.
Write the padlock picture
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'picture = [' ' \"..........\",' ' \"...####...\",' ' \"..#....#..\",' ' \"..#....#..\",' ' \".########.\",' ' \".###..###.\",' ' \".###..###.\",' ' \".########.\",' ']' '' '' 'def pixels():' ' white = bytes([255]) * 16' ' black = bytes([0]) * 16' ' data = b\"\"' ' for row in picture:' ' for dot in row:' ' data = data + (black if dot == \"#\" else white)' ' return data' > steps/lockpic.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the ECB script
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import os' 'from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes' 'from lockpic import picture, pixels' '' 'key = os.urandom(16)' 'ecb = Cipher(algorithms.AES(key), modes.ECB()).encryptor()' 'secret = ecb.update(pixels()) + ecb.finalize()' '' 'names = {}' 'print(\"The picture after AES in ECB mode, one letter for each different block:\")' 'for r in range(len(picture)):' ' line = \"\"' ' for c in range(10):' ' at = (r * 10 + c) * 16' ' block = secret[at:at + 16]' ' if block not in names:' ' names[block] = \"AB\"[len(names)]' ' line = line + names[block]' ' print(line)' 'print(\"different blocks:\", len(names), \"of\", len(secret) // 16)' > steps/ecb.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Encrypt the picture in ECB mode
docker exec jupyter python3 steps/ecb.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What ecb.py printed
| Line | Printed |
|---|---|
| 1 | AAAAAAAAAA |
| 2 | AAABBBBAAA |
| 5 | ABBBBBBBBA |
| 6 | ABBBAABBBA |
| Last | different blocks: 2 of 80 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsThe fix: an AEAD with a fresh nonce
Use an AEAD such as AES-GCM or ChaCha20-Poly1305. Each message gets a fresh 12-byte nonce, so equal blocks encrypt differently.
It also adds a 16-byte tag. Decryption checks the tag first and refuses anything changed, so nobody can swap or edit blocks unseen. Run gcm.py on the same picture.
Write the AES-GCM script
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import os' 'from cryptography.hazmat.primitives.ciphers.aead import AESGCM' 'from lockpic import pixels' '' 'key = AESGCM.generate_key(bit_length=128)' 'nonce = os.urandom(12)' 'sealed = AESGCM(key).encrypt(nonce, pixels(), b\"picture-1\")' 'body = sealed[:-16]' 'blocks = set(body[at:at + 16] for at in range(0, len(body), 16))' 'print(\"AES-GCM: different blocks:\", len(blocks), \"of\", len(body) // 16)' 'print(\"ciphertext bytes:\", len(body), \"tag bytes:\", len(sealed) - len(body))' '' 'changed = bytearray(sealed)' 'changed[5] = changed[5] ^ 1' 'try:' ' AESGCM(key).decrypt(nonce, bytes(changed), b\"picture-1\")' ' print(\"changed ciphertext: accepted\")' 'except Exception as error:' ' print(\"changed ciphertext: refused,\", type(error).__name__)' 'print(\"right ciphertext opens:\", AESGCM(key).decrypt(nonce, sealed, b\"picture-1\") == pixels())' > steps/gcm.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Seal the picture with AES-GCM
docker exec jupyter python3 steps/gcm.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think AES is safe in any mode, because AES itself is strong. The mode decides what leaks and whether changes are caught. Choose an AEAD mode, never ECB, and let a vetted library do it.
Check
Have a go
Check
3 questionsCatch ECB in code review
ECB rarely appears by accident in a review. It appears because a tutorial used it. A team writes the rule down, "no ECB anywhere", and checks it on every change.
The simplest check is a search of the code. Linters such as Bandit and Semgrep carry rules like it, and lesson 6 writes one.
Search the scripts for ECB
docker exec jupyter grep -n "modes.ECB" steps/ecb.py steps/gcm.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: spot ECB from the ciphertext
Spot ECB from the outside, the way an auditor does with only the ciphertext.
blocks(data, size) cuts bytes into pieces of size, in order. repeats(data, size) counts the blocks equal to an earlier block. looks_like_ecb(data, size=16) is True when any block repeats.
def blocks(data, size):
# Cut data into pieces of size bytes, in order.
return []
def repeats(data, size):
# How many blocks are equal to a block that came earlier?
return 0
def looks_like_ecb(data, size=16):
# True when any block repeats.
return False
Make a free account to save your work and track your progress.
Exit quiz
Have a go