Block Cipher Modes: ECB, CBC and CTR
AES encrypts 16 bytes. A file, a database column or a TLS record is longer, so something has to decide how the blocks are chained together. That something is the mode of operation, and it matters more than the cipher: AES in the wrong mode leaks the structure of the data, sometimes so clearly that you can see it with your eyes.
The lab: encrypt a picture
The lab encrypts a 32 × 32 picture (4 bytes per pixel, so one AES block is 4 pixels of a row) with real AES-128, block by block. Start with ECB and the padlock, then switch to CBC and CTR, and try the other pictures and keys.
Under ECB the padlock's outline survives encryption: the picture has only 16 distinct plaintext blocks, and ECB turns them into 16 distinct ciphertext blocks. The lab draws each ciphertext block in a shade taken from its first byte, so equal blocks look equal and the regions stay visible. Under CBC and CTR all 256 ciphertext blocks are different and the picture becomes noise. Changing the key changes the colours, not the leak.
The three modes
ECB (electronic codebook) encrypts every block independently: C_i = E(K, P_i). Equal plaintext blocks give equal ciphertext blocks, always. It is a codebook: a deterministic dictionary from blocks to blocks. ECB is not secure for more than one block of data, and it is the default in some old APIs (AES.new(key, AES.MODE_ECB), Java's Cipher.getInstance("AES") on most providers means AES/ECB/PKCS5Padding).
CBC (cipher block chaining) XORs each plaintext block with the previous ciphertext block before encrypting: C_i = E(K, P_i ⊕ C_(i−1)), with C_0 = IV. Equal blocks no longer look equal, because each depends on everything before it. The IV must be unpredictable (random) for each message: with a predictable IV, an attacker who can submit plaintexts can test guesses about earlier blocks (the flaw behind the 2011 BEAST attack on TLS 1.0, which used the last ciphertext block of the previous record as the next IV). CBC needs padding (next lesson) and is sequential to encrypt.
CTR (counter) turns the block cipher into a stream cipher: encrypt a counter block nonce ‖ i to get a keystream block and XOR it with the plaintext: C_i = P_i ⊕ E(K, nonce ‖ i). No padding, parallel in both directions, random access to any block. The price is the one-time-pad rule: a (key, nonce) pair must never repeat, or the keystream repeats (Nonce Reuse). CTR is also malleable: flipping a ciphertext bit flips the same plaintext bit.
The leak in bytes
Four 16-byte blocks, three of them identical, encrypted under the key from NIST SP 800-38A's examples. The program prints the first 4 bytes of each ciphertext block. The IV is fixed so the output is stable; a real CBC IV is os.urandom(16) per message.
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c") # SP 800-38A example key; real keys: os.urandom(16)
iv = bytes.fromhex("000102030405060708090a0b0c0d0e0f") # fixed here; real CBC IVs: os.urandom(16) per message
msg = b"ATTACK AT DAWN!!" * 3 + b"RETREAT AT DUSK!" # four 16-byte blocks, three identical
def run(mode):
e = Cipher(algorithms.AES(key), mode).encryptor()
return e.update(msg) + e.finalize()
for name, mode in [("ECB", modes.ECB()), ("CBC", modes.CBC(iv)), ("CTR", modes.CTR(iv))]:
ct = run(mode)
blocks = [ct[i:i + 16].hex()[:8] for i in range(0, len(ct), 16)]
print(f"{name}: {' '.join(blocks)} distinct blocks: {len(set(blocks))}/4")ECB: 541ff0c9 541ff0c9 541ff0c9 214922e9 distinct blocks: 2/4
CBC: d4d884b4 b0117a21 644a79f2 964a7d35 distinct blocks: 4/4
CTR: 11aa338d ee75da0f d7bedbc8 898fd550 distinct blocks: 4/4
ECB tells an eavesdropper "the first three blocks are the same message", without any key. In a database encrypted with ECB, equal values (the same salary, the same diagnosis) produce equal ciphertexts, which is enough for frequency analysis. The 2013 Adobe breach is the textbook case: passwords had been encrypted with 3DES in ECB mode, so everyone with the same password had the same ciphertext, and users' password hints next to the most common ciphertexts gave the passwords away.
The same result from OpenSSL in the sandbox (-nopad because the message is already a multiple of 16 bytes; xxd shows each block on a row):
printf 'ATTACK AT DAWN!!ATTACK AT DAWN!!ATTACK AT DAWN!!RETREAT AT DUSK!' > msg.txt
K=2b7e151628aed2a6abf7158809cf4f3c
IV=000102030405060708090a0b0c0d0e0f
echo "== ECB"
openssl enc -aes-128-ecb -K $K -nopad -in msg.txt | xxd -c 16 | cut -c 11-50
echo "== CBC"
openssl enc -aes-128-cbc -K $K -iv $IV -nopad -in msg.txt | xxd -c 16 | cut -c 11-50== ECB
541f f0c9 2b92 51ae 06c6 24c4 a8ab 2a85
541f f0c9 2b92 51ae 06c6 24c4 a8ab 2a85
541f f0c9 2b92 51ae 06c6 24c4 a8ab 2a85
2149 22e9 e1d3 9652 ee22 9912 a8ff b7f9
== CBC
d4d8 84b4 1d73 a432 10dd 016d 64d8 2e52
b011 7a21 8182 ee3b c8e3 9d90 93fb 3b27
644a 79f2 1522 3ce3 ecc9 89f1 bfa0 f246
964a 7d35 336c b582 34c6 a530 da0c 49d1
Python and OpenSSL agree byte for byte, as they must: the modes are standardised in NIST SP 800-38A.
What none of these modes gives you
ECB, CBC and CTR provide confidentiality only. None of them detects changes: in CBC, flipping a bit in C_(i−1) flips the same bit in P_i (and garbles P_(i−1)); in CTR, flipping a ciphertext bit flips the plaintext bit directly. Anyone who encrypts with these modes must add a MAC over the ciphertext (encrypt-then-MAC) or, much better, use an AEAD mode that does it for them.
How mode problems are detected
- Code and configuration:
MODE_ECB,modes.ECB(),"AES/ECB/...", bare"AES"in Java,aes-128-ecbin scripts; CBC with an IV that is constant, derived from the key, or a counter; CTR with a nonce that is not unique per key. - Ciphertext inspection: split ciphertext into 16-byte blocks and count duplicates. Any repeat in data longer than a few blocks is a strong sign of ECB (the same check reveals ECB in an unknown black-box system you are authorised to test). Identical first blocks for messages that start the same way mean a fixed CBC IV.
- Missing integrity: CBC or CTR ciphertext with no MAC, or a MAC over the plaintext checked after decryption.
How it is fixed
- New designs: AES-GCM or ChaCha20-Poly1305 (Authenticated Encryption). No separate MAC, no padding, one API call.
- Legacy CBC that must stay: random IV per message, encrypt-then-MAC with HMAC-SHA-256 under a separate key, constant-time MAC check before decrypting.
- ECB is acceptable only for encrypting a single random block, such as wrapping a key, and even there a dedicated key-wrap mode (AES-KW, RFC 3394) is the standard choice.
Pitfalls
- Believing CBC with a random IV is "secure enough" without a MAC: the padding-oracle lesson shows otherwise.
- Using a timestamp or a database row id as a CTR nonce without checking that it never repeats under the same key.
- Fixing ECB by "adding a random first block": the remaining blocks are still a codebook.
Practice
1. In the lab, why does the "letters" picture still leak under ECB but look like noise under CTR with the same key?
The letters are drawn with a few colours, so many 4-pixel blocks are identical; ECB maps identical blocks to identical ciphertext. CTR XORs every block with a different keystream block (the counter differs), so identical plaintext blocks give different ciphertexts.
2. A ciphertext of 4,096 bytes has 37 pairs of identical 16-byte blocks at 16-byte-aligned offsets. What do you conclude?
Almost certainly ECB. For CBC or CTR the chance of even one repeated block in 256 blocks is about 2^-113. Report it as "deterministic block encryption; equal plaintext blocks are revealed".
3. Change the CBC IV in the Python example to all zeros, then encrypt two messages that start with the same 16 bytes. What do you see?
The first ciphertext block is identical for both messages: with a fixed IV, CBC leaks equal prefixes. A random IV per message prevents it.
Test yourself
Why does the padlock stay visible under ECB in the lab?
- ECB encrypts only some blocks
- Equal plaintext blocks always give equal ciphertext blocks
- The key is too short
- ECB uses a fixed IV
What must be true of a CBC IV?
- It must be secret
- It must be unpredictable and fresh for each message
- It must equal the key
- It must be all zeros
Which statement about CTR mode is true?
- It needs padding
- Reusing a nonce with the same key repeats the keystream
- It detects tampering
- It cannot be parallelised
In the Python example, how many distinct ciphertext blocks did ECB produce for the four-block message?
- 1
- 2
- 3
- 4