Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Why ECB mode leaks patterns

After this lesson: I can show why ECB mode leaks patterns and replace it with AES-GCM.

60 min lesson6 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can show why ECB mode leaks patterns and replace it with AES-GCM.

Key words

WordWhat it meansExample
Block ciphera cipher that scrambles 16 bytes at a timeAES
Modethe rule for using a block cipher on longer data
ECBthe mode that scrambles every block alone, the same way
AEADencryption that also proves the data was not changed
Noncea value used once per message
Tagthe 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

ECB 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

Code: python
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Encrypt 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

Command
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

Command
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

Command
docker exec jupyter python3 steps/ecb.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What ecb.py printed

LinePrinted
1AAAAAAAAAA
2AAABBBBAAA
5ABBBBBBBBA
6ABBBAABBBA
Lastdifferent blocks: 2 of 80

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The 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

Command
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

Command
docker exec jupyter python3 steps/gcm.py

Shown 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Catch 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

Command
docker exec jupyter grep -n "modes.ECB" steps/ecb.py steps/gcm.py

Shown 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.