Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 40 ยท Symmetric Encryption

Modes of Operation: ECB, CBC, CTR

See how ECB leaks patterns, how CBC chains blocks with an IV and padding, how CTR turns a block cipher into a stream cipher, and why all three are malleable.

A block cipher such as AES encrypts exactly one block, 16 bytes. Real messages are longer: emails, files, database rows. A mode of operation is the recipe that says how to apply the block cipher repeatedly to a long message. The cipher can be perfect and the result still insecure if the mode is wrong.

This lesson implements the three classic modes, ECB, CBC and CTR, using a small pure-Python block cipher so everything runs in your browser and you can see the bytes. The ideas are identical for AES. You will watch ECB leak the shape of a picture, see why CBC needs padding and a fresh initialization vector, and discover that none of the three notices when someone tampers with the ciphertext.

A toy block cipher to experiment with

To keep the code short we use an 8-byte block cipher built as a Feistel network: split the block in halves, and in each round replace the left half with the right and the right with left XOR F(right, key), where F is a scrambling function (here a truncated SHA-256). A Feistel network is always reversible, whatever F does, which is why DES and many other ciphers are built this way.

Toy cipher. Its block is 8 bytes and it has not been analysed. It exists only to demonstrate modes. Real code uses AES from a reviewed library.

The first experiment is ECB (Electronic Codebook), the obvious mode: cut the message into blocks and encrypt each one independently with the same key. Because the cipher is deterministic, equal plaintext blocks give equal ciphertext blocks. Below, a tiny 8 by 10 picture is stored one row per block. Each row is exactly one 8-byte block, so we can see which rows repeat.

Python ECB leaks the pattern of the data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Ten rows produce only six distinct ciphertext blocks, and the label sequence ABCDEDFCBA is far from random: the first and last rows share a label, so do the second and the second-to-last, and so on, mirroring the picture. An eavesdropper who has never seen the key still learns where the blank rows are, which rows are identical, and the rough structure of the picture. With real images encrypted by AES in ECB mode, the outline of the picture stays clearly visible; this is the well-known "ECB penguin" problem. ECB is also not randomized: the same message always encrypts to the same bytes, so an attacker can see when something repeats and can cut and paste blocks between messages.

Never use ECB for data longer than one block. It is only acceptable for encrypting a single random-looking block, such as a key.

Padding

Messages are rarely a multiple of the block size. Block modes that need full blocks (ECB and CBC) pad the last block. The standard scheme is PKCS#7: add n bytes, each of value n, where n is the number of bytes needed (1 to the block size). A message that already fills a block gets a whole extra block of padding, so removing padding is never ambiguous: look at the last byte, and remove that many bytes.

CBC: chaining blocks

CBC (Cipher Block Chaining) XORs each plaintext block with the previous ciphertext block before encrypting it. For the first block there is no previous ciphertext, so a random initialization vector (IV) takes its place. The IV is not secret and is sent in front of the ciphertext, but it must be unpredictable and fresh for every message.

flowchart LR
    IV["IV"] --> X1(("XOR"))
    P1["Plaintext 1"] --> X1
    X1 --> E1["Encrypt"] --> C1["Cipher 1"]
    C1 --> X2(("XOR"))
    P2["Plaintext 2"] --> X2
    X2 --> E2["Encrypt"] --> C2["Cipher 2"]

In CBC each ciphertext block feeds the next block's encryption, so equal plaintext blocks no longer give equal ciphertext blocks.

Chaining fixes the repetition problem: the same plaintext block encrypts differently depending on what came before. The price is that encryption must be done one block after the other (decryption can run in parallel, because every ciphertext block is already known).

CTR: a block cipher as a stream cipher

CTR (Counter mode) never runs the plaintext through the cipher. It encrypts a sequence of counter values (a nonce followed by 0, 1, 2, ...) to create a keystream, and XORs that with the message. This is a stream cipher built from a block cipher, so no padding is needed and the ciphertext has exactly the message's length. Blocks can be processed in parallel in both directions. As with every stream cipher, the nonce and counter pair must never repeat under one key.

The next program implements PKCS#7 padding, CBC and CTR, and shows that the same repeating plaintext no longer repeats in the output.

Python CBC and CTR with padding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The message contains the same 8 bytes three times, but the three CBC blocks all differ, and so do the three CTR blocks. Padding added a whole extra block for the 24-byte message (CBC output is 32 bytes), while CTR needed none.

CFB and OFB: two more stream-like modes

Two older modes also turn a block cipher into a stream cipher. Both use only the cipher's encryption function, in both directions, and neither needs padding.

  • CFB (Cipher Feedback): encrypt the previous ciphertext block (the IV for the first one) and XOR the result with the plaintext. The ciphertext feeds back into the next step, as in CBC, so errors propagate for one extra block when a ciphertext bit is damaged. It can be run on units smaller than a block (CFB-8 handles one byte at a time), which once suited terminal links.
  • OFB (Output Feedback): repeatedly encrypt the IV to create a keystream (K1 = E(IV), K2 = E(K1), ...) and XOR it with the plaintext. The keystream does not depend on the data at all, so it can be precomputed, and a flipped ciphertext bit flips exactly the same plaintext bit and nothing else. Reusing an IV repeats the keystream, with the same disastrous result as in CTR.

Like CTR, both give confidentiality only: nothing detects tampering. Today CTR and GCM are preferred because they allow parallelism, and CFB and OFB mostly survive in old protocols.

Python CFB and OFB with the toy cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reusing the IV

An IV that repeats, or that an attacker can predict, brings leaks back. If two messages are encrypted with the same key and the same IV in CBC, any common beginning produces identical ciphertext blocks at the start, so the attacker learns exactly how long the shared prefix is. Choose a fresh random IV for each message (and for CBC, never a simple counter). For CTR the situation is worse: a repeated nonce reuses the keystream and leaks P1 XOR P2.

Modes do not provide integrity

All three modes protect only secrecy. Nothing in them checks whether the ciphertext was modified, and the way they break is instructive.

  • In CTR, flipping a bit of the ciphertext flips exactly that bit of the plaintext.
  • In CBC, flipping a bit in ciphertext block i flips the same bit in plaintext block i+1 (because of the XOR with the previous ciphertext) and turns plaintext block i into unpredictable garbage.

An attacker who knows or can guess the plaintext can therefore edit it without the key. The example changes the amount in a payment order, knowing only the position of the digit.

Python Bit-flipping a CBC message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Block 0 decrypts to garbage, which a careful application might notice. But the attacker chose which block to damage: in a real protocol the first block could be a header the application ignores. The only robust answer is to authenticate the ciphertext, which is what the next two lessons do: first with authenticated encryption, then with the message authentication codes that underpin it.

Choosing a mode in practice

Mode Padding Parallel Main danger
ECB Yes Yes Leaks patterns; never use
CBC Yes Decrypt only Predictable IV, padding oracles, malleability
CTR No Yes Nonce reuse, malleability
GCM, ChaCha20-Poly1305 No GCM yes Nonce reuse (but tamper-proof)

For new designs, use an authenticated mode and let the library handle details.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does ECB mode leak information about the plaintext?

    Each block is encrypted independently with the same key, so repetition in the plaintext shows up as repetition in the ciphertext. That reveals structure, such as the outline of an image.
  2. 2. What is the purpose of the IV in CBC mode?

    The IV acts as the 'previous ciphertext block' for the first block. It is public, but it must be fresh and unpredictable for each message.
  3. 3. In CBC, an attacker flips one bit in ciphertext block 2. What happens on decryption?

    Block 2 decrypts to random-looking garbage, while block 3 is XORed with the modified block 2, so its corresponding bit flips predictably.
  4. 4. Which mode does not need padding?

    CTR turns the block cipher into a keystream generator and XORs it with the data, so the last partial block is simply truncated.
  5. 5. A message is exactly 16 bytes long and is encrypted in CBC mode with a 16-byte block cipher and PKCS#7 padding. How long is the ciphertext, not counting the IV?

    PKCS#7 always adds at least one byte. A full block of input therefore gets a whole extra block of padding bytes (value 16), giving 32 bytes.

Summary

  • A mode of operation extends a one-block cipher to messages of any length; the mode decides whether the result is secure.
  • ECB encrypts blocks independently and leaks repetition; never use it for real data.
  • CBC chains blocks with a fresh unpredictable IV and needs padding; CTR builds a keystream from counters and needs a unique nonce.
  • None of these modes detects tampering; bit-flipping lets an attacker edit known plaintext. Add authentication.

Next: Authenticated Encryption: GCM and ChaCha20-Poly1305.