ECB Attacks
Electronic Codebook encrypts each block independently and deterministically. Identical plaintext blocks produce identical ciphertext blocks, which leaks structure at a glance — and with a chosen-plaintext oracle it becomes a decryption machine that recovers an appended secret one byte at a time.
This is a mode defect, not a weak algorithm
Detecting ECB from ciphertext
The classic test is to decode the value and count repeated 16-byte blocks. It works because ECB is the only common mode where two identical plaintext blocks at different positions produce two identical ciphertext blocks — every other mode mixes position or a per-message randomiser into the input.
import base64
from collections import Counter
def blocks(data, size=16):
return [data[i:i + size] for i in range(0, len(data) - size + 1, size)]
def ecb_score(ciphertext):
"""Number of repeated 16-byte blocks. ECB gives a positive score on
anything with structure; a chaining mode gives zero on real data."""
chunks = blocks(ciphertext)
counts = Counter(chunks)
return sum(c - 1 for c in counts.values() if c > 1), len(chunks)
raw = base64.b64decode(open("cookie.b64", "rb").read())
repeats, total = ecb_score(raw)
print(f"{repeats} duplicate blocks across {total}")
# always print the offenders: an all-zero block is not a finding
for chunk, count in Counter(blocks(raw)).most_common(3):
if count > 1:
print(count, chunk.hex(), "all-zero" if chunk == bytes(16) else "")Treat the count as a screen rather than a verdict. Real plaintext has little 16-byte repetition, so a positive score on a text-bearing value is meaningful; but a score on a binary format may be entirely benign. The stronger test needs no repetition at all: submit the same input twice and compare. A deterministic cipher returns the same bytes, and a chaining mode with a random IV cannot.
| Signal | Reliability | What it means |
|---|---|---|
| Two identical plaintexts produce identical ciphertext | Conclusive | Any chaining mode with a random IV or nonce differs on every call. Test by submitting the same input twice. |
| The same 16 bytes repeat inside one ciphertext | Strong | Requires repeated plaintext blocks. Check the offenders — all-zero blocks and image headers repeat legitimately. |
| Ciphertext length is a multiple of 16 with no separate IV | Weak | Consistent with ECB, but also with a zero IV stored elsewhere, or with the IV prepended and not recognised. |
| Flipping one bit changes one block only | Strong | In CBC the same flip corrupts the whole next block. This needs a chosen-plaintext oracle to observe. |
| The value is shorter than the plaintext plus 16 bytes | Weak | No room for an IV does not prove ECB; the IV may live in a separate field or be derived from the key. |
Block alignment
Block ciphers are position-blind in ECB, so the attacker controls which block a byte lands in by controlling how many bytes precede it. If the target byte sits at the end of a block, then everything before it in that block is known once the preceding bytes are known — and the attacker can submit a plaintext whose first block equals that known prefix plus one candidate byte, then compare first blocks.
With a secret of unknown length appended to attacker input, the alignment is chosen so the unknown byte is the last
byte of the first block: send pad = 16 - (len(known) mod 16) - 1
filler bytes. When the known prefix reaches a multiple of 16 the filler drops to 15 and the block index advances,
which is why the same loop works indefinitely rather than only for the first block.
| Known bytes | Filler sent | Position of the unknown byte |
|---|---|---|
| 0 | 15 | Last byte of block 1 |
| 1 | 14 | Last byte of block 1 |
| 15 | 0 | Last byte of block 1 |
| 16 | 15 | Last byte of block 2 |
Byte-at-a-time decryption
The oracle below is a self-contained simulation: a fixed key, a secret appended, PKCS#7 padding, ECB. The attack
needs three capabilities — submit plaintext, receive ciphertext of input || secret,
and compare bytes — and no knowledge of the key.
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
KEY = os.urandom(16)
SECRET = b"the-admin-reset-token-is-9f2c" # what we are recovering
def oracle(attacker_input: bytes) -> bytes:
"""The victim: encrypts attacker_input || SECRET under a fixed key."""
plaintext = attacker_input + SECRET
pad = 16 - len(plaintext) % 16
plaintext += bytes([pad]) * pad
enc = Cipher(algorithms.AES(KEY), modes.ECB()).encryptor()
return enc.update(plaintext) + enc.finalize()
def recover_secret():
known = b""
while True:
pad_len = 16 - (len(known) % 16) - 1
prefix = b"A" * pad_len
target_block = oracle(prefix)[:16]
for candidate in range(256):
probe = prefix + known + bytes([candidate])
if oracle(probe)[:16] == target_block:
known += bytes([candidate])
break
else:
return known # no byte matched: the value was padding
print(known)
if __name__ == "__main__":
print(recover_secret())It runs in 16 × 256 oracle calls per block, so a 32-byte token falls in roughly 8,000 requests — trivial against a route with no rate limit. The loop terminates when no candidate matches, which happens only after the real secret is exhausted and the trailing bytes are padding.
The oracle is the vulnerability
ECB among the modes
ECB is not the only mode without integrity, and CBC is not automatically safe. What distinguishes ECB is that it leaks equality without any error channel, so a reviewer can prove it from a single captured value.
| Mode | IV / nonce | Parallel | What leaks | Integrity |
|---|---|---|---|---|
| ECB | None | Yes | Equality of plaintext blocks; full chosen-plaintext decryption with an oracle | None |
| CBC | Random, unpredictable | Encryption no, decryption yes | First-block equality if the IV is fixed; padding validity when errors differ | None — padding oracle risk |
| CTR | Unique nonce, never reused | Yes | Keystream reuse if a nonce repeats — recovers plaintext by XOR | None |
| GCM | Unique nonce, never reused | Yes | Nothing beyond length; nonce reuse is catastrophic | Yes — authentication tag |
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
# no IV, no nonce, no authentication: every block stands alone
enc = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
ciphertext = enc.update(plaintext) + enc.finalize()from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
# no IV, no nonce, no authentication: every block stands alone
enc = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
ciphertext = enc.update(plaintext) + enc.finalize()from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# a fresh nonce per message, and the tag is verified on decrypt
nonce = os.urandom(12)
ciphertext = AESGCM(key).encrypt(nonce, plaintext, associated_data)
# store nonce || ciphertext; decryption raises on any tamperingfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM
# a fresh nonce per message, and the tag is verified on decrypt
nonce = os.urandom(12)
ciphertext = AESGCM(key).encrypt(nonce, plaintext, associated_data)
# store nonce || ciphertext; decryption raises on any tamperingHow it ships
Nobody chooses ECB deliberately. It arrives through a default, and the defaults are old: several libraries predate the expectation that a mode must be named. The list below is where to look first, because each of these is a single argument away from safe.
| Construction | Why it resolves to ECB | Fix |
|---|---|---|
Java Cipher.getInstance("AES") |
The JCA pads the transformation to AES/ECB/PKCS5Padding |
Name AES/GCM/NoPadding explicitly |
OpenSSL enc -aes-128-ecb |
The mode is in the cipher name chosen at the command line | Use a real AEAD tool, not enc |
.NET CipherMode.ECB |
An explicit enum value, often copied from a sample | AesGcm in modern .NET |
Legacy mcrypt / Node createCipher |
Removed or deprecated precisely because they picked a mode for you | crypto.createCipheriv with GCM |
| Home-grown "encrypt this string" helpers | Usually the shortest working sample, which is ECB | Replace the helper, then find its call sites |
| Check | Expected | Where to look |
|---|---|---|
| Ciphertext has been examined at the block level, not as one opaque string | Base64 decoded first, then split into 16-byte chunks and counted for duplicates | The captured value |
| Determinism was tested by resubmitting identical plaintext | Identical ciphertext confirms ECB and is stronger evidence than a repeated block | Two requests |
| Any repeated block is explained before it is reported | All-zero blocks and structured binaries repeat for benign reasons | The finding text |
| The oracle assumption is stated | The attacker can submit plaintext and read ciphertext of the concatenation | The exploitation notes |
| The recommended fix changes the mode and adds authentication | AES-GCM or AES-CBC with encrypt-then-MAC — not a longer key | The remediation |
Evidence to Capture
An ECB finding is only persuasive if the reviewer can see the block structure themselves:
Decoded ciphertext and block offsets: Base64 or hex, split at 16 bytes, with the duplicate offsets marked. Include the decoded byte length so the reader can verify the split.
The two requests that prove determinism: Identical submission, identical output, with timestamps. This works even when the plaintext contains no repeated block.
The oracle, if one is reachable: A route where the attacker supplies input that ends up adjacent to the secret. Without it the finding is still valid, but the impact claim should not mention decryption.
Recovered plaintext or a prefix of it: Even eight bytes of a token demonstrates the impact in a way a description does not. Redact the remainder.
The configuration that selected the mode: The line of code or the framework default that produced ECB. That is what the fix has to change.
When the Signal Lies
Repeated blocks are suggestive, not conclusive. Four cases produce them without ECB:
- All-zero or all-0xff blocks: Padding in a fixed-width binary format, sparsely populated structs, and reserved fields all produce a block of zeros. Never report one.
- Binary headers at block alignment: A bitmap or archive with repeated header bytes can align into identical 16-byte chunks. Look at the offsets relative to the file start.
- Compressed or encoded payloads: Long runs of one character survive compression in some formats, and base64 of repetitive text produces repeating patterns that are not block-aligned.
- The ciphertext is not a ciphertext: A hash, a random identifier, or a signed value can contain repeated substrings by chance. Confirm the value is decryptable before analysing it as ciphertext.
ECB Review Checklist
Run this when a codebase constructs a cipher directly rather than through an AEAD helper:
- ☐ Every cipher construction names an explicit mode — no bare default
- ☐ No ECB, including framework defaults that are not obvious at the call site
- ☐ The IV or nonce is generated per message from a CSPRNG and stored with the ciphertext
- ☐ The IV is not derived from the key, a counter shared across messages, or the message index alone
- ☐ The ciphertext is authenticated, or the format is visibly encrypt-then-MAC with a separate key
- ☐ Decryption failures return one uniform error
- ☐ No format distinguishes padding failure from MAC failure in a response the attacker can observe
- ☐ The secret is never encrypted adjacent to attacker-controlled input
- ☐ The encrypted value is not compared for equality as a shortcut
- ☐ Encryption keys are not reused across tenants
Fixing It Properly
The fix is a mode change plus authentication. Anything smaller leaves the oracle in place:
Why a MAC alone does not fix the leak
Adding an HMAC over the ciphertext stops tampering and stops the padding oracle, but it does not stop an attacker who can encrypt through the legitimate route: the oracle returns a valid tag every time. Equality still leaks to anyone who captures the value, and byte-at-a-time still works if the secret is adjacent to attacker input, because each probe is a legitimate encryption. Authentication and a chaining mode are separate requirements, and ECB fails the second one.
Detecting the attack from the defender's side
The signature is a burst of near-identical requests from one session, each a single byte different from the last, followed by a request with one more byte. A rate limit turns an eight-thousand-request attack into a week, but it does not stop a patient attacker. Treat the pattern as a detection that buys time, and the mode change as the fix.
ECB Practice
Exercises where the oracle is supplied for you, so the work is the alignment and the bookkeeping rather than the plumbing.
Related Cryptography Guides
Crypto Fundamentals
Block modes, IVs and why ECB is the only mode that leaks equality.
Padding Oracle
The other CBC failure — when the error message is the oracle rather than the ciphertext.
RSA Attacks
Deterministic encryption without a randomiser is the same class of mistake in public-key form.
Cryptography Remediation
The fix catalogue for cryptographic findings, including the AEAD migration patterns.