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

Free lesson

Never reuse a nonce

After this lesson: I can show what a reused nonce leaks and make sure every message gets a fresh one.

60 min lesson5 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

Two messages, one mistake

A team builds a chat app for an exams office. To keep it simple, they set the nonce to zeros once and use it for every message.

Every message is encrypted with a strong cipher. Yet one guessed greeting is enough to read the next message. You will see why, and fix it.

The one rule

Warning

You read only the messages your own toy sends, in your own lab. Capturing and decrypting someone else's traffic without permission is illegal. In the UK 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 what a reused nonce leaks and make sure every message gets a fresh one.

Key words

WordWhat it meansExample
Stream ciphera cipher that XORs data with a keystreamChaCha20
Keystreamthe secret bytes made from the key and nonce
XORcombining bits so the same value twice cancels out
Nonce reuseusing one key and nonce for two messages
Known plaintexta message the attacker already knows or guesses

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

The same keystream twice cancels out

ChaCha20, and AES in CTR or GCM mode, make a keystream from the key and the nonce, then XOR it with the message.

With the same key and nonce, two messages get the same keystream. XOR the two ciphertexts and the keystream cancels. What is left is the two plaintexts XORed.

Try it: cancel a keystream

Code: python
import hashlib

def keystream(key, nonce, n):
    return hashlib.sha256(key + nonce).digest()[:n]

key, nonce = b"k" * 16, b"same"
p1, p2 = b"MEET AT TEN", b"PIN IS 4821"
s = keystream(key, nonce, len(p1))
c1 = bytes(a ^ b for a, b in zip(p1, s))
c2 = bytes(a ^ b for a, b in zip(p2, s))
print(bytes(a ^ b ^ c for a, b, c in zip(c1, c2, p1)))
# A toy stream, not a real cipher. Change nonce for c2 only: what is printed now?

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

Read the second message

nonce.py sends two messages with ChaCha20 under one key and a nonce of zeros. Every chat starts with the same greeting, so the attacker knows message 1.

Run it to see the XOR rule hold, and the second message read without the key.

Write the reused nonce chat

Command
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import os' 'from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes' '' 'KEY = os.urandom(32)' 'NONCE = bytes(16)' '' '' 'def send(text):' '    box = Cipher(algorithms.ChaCha20(KEY, NONCE), mode=None).encryptor()' '    return box.update(text)' '' '' 'first = b\"Hello from the exams office.\"' 'second = b\"Paper 2 starts 09:30 in B14.\"' 'c1, c2 = send(first), send(second)' 'print(\"same nonce twice:\", c1[:4].hex() == send(first)[:4].hex())' 'mixed = bytes(a ^ b for a, b in zip(c1, c2))' 'both = bytes(a ^ b for a, b in zip(first, second))' 'print(\"c1 XOR c2 equals p1 XOR p2:\", mixed == both)' 'guess = bytes(a ^ b for a, b in zip(mixed, first))' 'print(\"knowing message 1 reveals message 2:\", guess.decode())' > steps/nonce.py"

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

Send two messages with one nonce

Command
docker exec jupyter python3 steps/nonce.py

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

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: a fresh nonce every time

Make a new nonce for every message and send it beside the ciphertext. A random 12-byte nonce from os.urandom is fine for up to about four billion messages a key. A counter that never repeats works too.

Use an AEAD, ChaCha20-Poly1305 here. With GCM, one repeat also lets an attacker forge tags.

Write the fixed chat

Command
docker exec jupyter sh -c "mkdir -p steps && printf '%s\n' 'import os' 'from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305' '' 'KEY = ChaCha20Poly1305.generate_key()' 'seen = set()' '' '' 'def send(text):' '    nonce = os.urandom(12)' '    seen.add(nonce)' '    return nonce + ChaCha20Poly1305(KEY).encrypt(nonce, text, None)' '' '' 'a = send(b\"Hello from the exams office.\")' 'b = send(b\"Hello from the exams office.\")' 'print(\"same message, same ciphertext:\", a == b)' 'print(\"nonces used:\", len(seen), \"for 2 messages\")' 'for n in range(10000):' '    send(b\"x\")' 'print(\"nonces used:\", len(seen), \"for 10002 messages\")' 'print(\"opens:\", ChaCha20Poly1305(KEY).decrypt(a[:12], a[12:], None).decode())' > steps/fresh.py"

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

Send messages with fresh nonces

Command
docker exec jupyter python3 steps/fresh.py

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

A common mistake

Warning

Many people think the nonce must be secret, so they hide it or derive it from the key. A nonce only has to be unique for its key. Send it in the clear with each message, and never let it repeat.

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

How a team catches it

A constant nonce is easy to find in review: search for a nonce built from fixed bytes. A unit test encrypts the same message twice and asserts the two outputs differ.

A service can also log nonces it has used with a key and alert on a repeat.

Search for a fixed nonce

Command
docker exec jupyter grep -n "NONCE = " steps/nonce.py steps/fresh.py

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

Assignment: read and catch reuse

Show what a reused nonce gives away, then catch it in a log.

xor(a, b) XORs two byte strings as far as the shorter. recover(c1, c2, p1) returns the second plaintext from two ciphertexts made with one key and nonce and the first plaintext. reused(nonces) returns a sorted list of the nonces that appear more than once, each once.

Code: python
def xor(a, b):
    # XOR two byte strings, as long as the shorter one.
    return b""


def recover(c1, c2, p1):
    # Two ciphertexts made with the same key and nonce, and the first plaintext.
    # Return the second plaintext.
    return b""


def reused(nonces):
    # A sorted list of the nonces that appear more than once, each listed once.
    return []

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.