Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

Modern symmetric encryption

By the end of this chapter, you'll be able to

  • Explain how a small key and a nonce produce a keystream
  • Tell stream ciphers and block ciphers apart
  • Recognise what ECB mode leaks on repetitive data
  • Name the algorithms to use today: AES-GCM and ChaCha20-Poly1305

Symmetric: the same key on both sides

Encryption is symmetric when the same key is used to encrypt and to decrypt, like the one-time pad. The two current standards are AES (Advanced Encryption Standard, chosen in 2001 after a public competition) and ChaCha20. They use 128- or 256-bit keys.

These algorithms are too long to write here. To understand their idea without reimplementing them, we will build a toy: a stream cipher whose stream is produced by SHA-256. This toy is for learning, never for protecting real data.

A stream from a small key

Idea: we compute SHA-256(key + nonce + counter) for counter = 0, 1, 2…, and join the results. We get a keystream as long as we want, unpredictable without the key. We then combine it with the message by XOR, like a one-time pad.

The nonce (number used once) is a value that changes with every message, and that does not need to be secret: it is sent along with the ciphertext. Thanks to it, two messages encrypted with the same key use different streams.

The nonce travels in clear with the ciphertext: the recipient needs it to recompute the stream.

Step 5 of 5
Text description of the animation
  1. The same small key is used for thousands of messages.
  2. A new value for every message, for example a counter.
  3. We produce as many 32-byte blocks as needed to cover the message.
  4. XOR makes the message unreadable; the same XOR restores it.
  5. The nonce travels in clear with the ciphertext: the recipient needs it to recompute the stream.
import hashlib

def keystream(key, nonce, length):
    """Pseudo-random stream: blocks SHA-256(key | nonce | counter). Teaching toy!"""
    output, counter = b"", 0
    while len(output) < length:
        output += hashlib.sha256(key + nonce + counter.to_bytes(8, "big")).digest()
        counter += 1
    return output[:length]

def encrypt(key, nonce, data):
    return bytes(d ^ s for d, s in zip(data, keystream(key, nonce, len(data))))

key = bytes(range(32))                       # for real: secrets.token_bytes(32)
message = "Association board meeting on Saturday at 10 am".encode()

c1 = encrypt(key, b"nonce-001", message)
c2 = encrypt(key, b"nonce-002", message)     # same message, other nonce
print("ciphertext 1:", c1.hex()[:40], "...")
print("ciphertext 2:", c2.hex()[:40], "...")
print("decrypted   :", encrypt(key, b"nonce-001", c1).decode())
ciphertext 1: 1f8300f53f2c15b0421478c3ff3181231c8b604f ...
ciphertext 2: e47026b16f3da0ef2bf1a5f0d4e923a3bd4de184 ...
decrypted   : Association board meeting on Saturday at 10 am

The same message gives two unrelated ciphertexts, thanks to the nonce. And the same function decrypts, since it is an XOR. ChaCha20 follows exactly this scheme, with a function much faster than SHA-256 and designed for this purpose.

Block ciphers and their modes

AES, for its part, is a block cipher: it turns a 16-byte block into another 16-byte block, with the key. To encrypt a long message, you must decide how to chain the blocks: that is the mode of operation.

  • ECB (Electronic Codebook): each block is encrypted on its own, with the same key. Never use it, see the pitfall below.
  • CTR (Counter): AES encrypts a counter to produce a stream, combined by XOR. That is our toy, with AES instead of SHA-256.
  • GCM (Galois/Counter Mode): CTR plus an authentication tag that detects any change. It is the recommended mode.

Today, we choose authenticated encryption (AEAD, Authenticated Encryption with Associated Data): AES-256-GCM or ChaCha20-Poly1305. In Python, they are in the cryptography library, installed with pip; the standard library does not include them.

Mini-lab: the nonce changes everythingPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: nonce reuse

A developer wrote nonce = b"fixed" "to keep things simple". Two messages were encrypted with the same key:

  • m1 = b"Amount due: 015000 F CFA...." (it is an invoice template, so known to everyone);
  • m2, an unknown message, of the same length.

With the chapter's encrypt function, produce c1 and c2, then show that a spy who only knows c1, c2 and m1 recovers m2, without the key. Take m2 = b"Safe combination code: 4471".

Hint 1
Same key and same nonce means the same stream: c1 = m1 ^ stream and c2 = m2 ^ stream.
Hint 2
Compute c1 ^ c2 ^ m1 byte by byte: the stream cancels out, and so does m1.
Show the solution and common mistakes
import hashlib

def keystream(key, nonce, length):
    output, counter = b"", 0
    while len(output) < length:
        output += hashlib.sha256(key + nonce + counter.to_bytes(8, "big")).digest()
        counter += 1
    return output[:length]

def encrypt(key, nonce, data):
    return bytes(d ^ s for d, s in zip(data, keystream(key, nonce, len(data))))

key = bytes(32)
m1 = b"Amount due: 015000 F CFA...."
m2 = b"Safe combination code: 4471"
c1 = encrypt(key, b"fixed", m1)
c2 = encrypt(key, b"fixed", m2)

# The spy only uses c1, c2 and m1:
recovered = bytes(a ^ b ^ c for a, b, c in zip(c1, c2, m1))
print(recovered.decode())
Safe combination code: 4471

This is the reused one-time pad pitfall, in a modern system. In 2017, the KRACK attack against WPA2 Wi-Fi precisely forced nonces to be reused.

Common mistakes:

  • Thinking the nonce must stay secret: it travels in clear, what matters is that it is unique, not secret.
  • Drawing a random nonce that is too short (a few bytes): two messages end up getting the same one by chance.
  • Believing that encryption without authentication protects integrity: the ciphertext can be modified, as the next chapter shows.

Summary

  1. 1Modern symmetric encryption produces a stream from a small key and a unique nonce.
  2. 2The nonce is not secret, but it must never be reused with the same key.
  3. 3ECB mode encrypts identical blocks the same way and shows the patterns.
  4. 4Today we use authenticated encryption: AES-256-GCM or ChaCha20-Poly1305, never a home-made algorithm.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.