How counter mode turns AES into a keystream

Short answer: Counter mode encrypts a counter block and xors the result with the plaintext. The fragment increments the last four bytes as a big-endian integer, which is the NIST SP 800-38A counter. Decryption is the same xor. The plaintext does not pass through the block cipher.


What the problem actually asks

A block cipher can generate a pad instead of wrapping the plaintext. The pad is the encryption of successive counters. The plaintext is xored with the pad, so a one-block change in the plaintext costs one counter encryption and no neighboring block. The counter value under one key has to be unique for every block. A repeat repeats the pad. Counter mode does not authenticate. A flipped ciphertext bit flips the matching plaintext bit and leaves everything else alone.


What the algorithm guarantees

The same key and counter reproduce the same pad. Any length that is a whole number of bytes can be xored, up to the last partial block. The example counter increments a 32-bit suffix. A deployment that needs more than 2^32 blocks under one prefix has to give those blocks a wider unique counter. The mode provides confidentiality only while the counters stay unique, and it provides no integrity.


The working steps

  1. Choose a counter block that will not repeat under the same key.
  2. Encrypt the counter with the block cipher.
  3. Xor the keystream with the next plaintext bytes.
  4. Increment the last four bytes and repeat until the message is consumed.

Approaches that look simpler and fail

Approach Why it fails when a counter is repeated
Restart the same counter for a second message The pad repeats. The xor of the ciphertexts is the xor of the plaintexts.
Increment the whole 16-byte block as if it were little-endian This NIST counter increments the last four bytes as a big-endian integer. A different increment is a different keystream.
Encrypt the plaintext and then xor the counter Counter mode encrypts the counter. The plaintext meets the cipher only at the xor.
Rely on the xor to detect a modified ciphertext A flipped bit decrypts to a flipped bit. A tag is a separate check.

GCM is counter mode plus GHASH. The fragment is the counter keystream.


A working example

This Python fragment encrypts the NIST SP 800-38A counter block and xors it with one plaintext block. It prints 874d6191b620e3261bef6864990db6ce.

def _xtime(a: int) -> int:
    return ((a << 1) ^ 0x1B) & 0xFF if a & 0x80 else (a << 1) & 0xFF

def _gmul(a: int, b: int) -> int:
    p = 0
    for _ in range(8):
        if b & 1:
            p ^= a
        a = _xtime(a)
        b >>= 1
    return p

def _sbox() -> list[int]:
    box = []
    for x in range(256):
        inv = 0 if x == 0 else next(i for i in range(1, 256) if _gmul(x, i) == 1)
        y = 0
        for i in range(8):
            bit = (inv >> i) ^ (inv >> ((i + 4) % 8)) ^ (inv >> ((i + 5) % 8))
            bit ^= (inv >> ((i + 6) % 8)) ^ (inv >> ((i + 7) % 8)) ^ (0x63 >> i)
            y |= (bit & 1) << i
        box.append(y)
    return box

_S = _sbox()

def aes128_encrypt(block: bytes, key: bytes) -> bytes:
    words = list(key)
    rcon = 1
    while len(words) < 176:
        t = words[-4:]
        if len(words) % 16 == 0:
            t = t[1:] + t[:1]
            t = [_S[b] for b in t]
            t[0] ^= rcon
            rcon = _xtime(rcon)
        earlier = words[-16:-12]
        words.extend(earlier[i] ^ t[i] for i in range(4))
    state = list(block)

    def add(rnd: int) -> None:
        rk = words[rnd * 16 : (rnd + 1) * 16]
        for i in range(16):
            state[i] ^= rk[i]

    def sub() -> None:
        for i in range(16):
            state[i] = _S[state[i]]

    def shift() -> None:
        for r in range(1, 4):
            row = [state[r + 4 * c] for c in range(4)]
            row = row[r:] + row[:r]
            for c in range(4):
                state[r + 4 * c] = row[c]

    def mix() -> None:
        for c in range(4):
            col = state[4 * c : 4 * c + 4]
            state[4 * c] = _gmul(col[0], 2) ^ _gmul(col[1], 3) ^ col[2] ^ col[3]
            state[4 * c + 1] = col[0] ^ _gmul(col[1], 2) ^ _gmul(col[2], 3) ^ col[3]
            state[4 * c + 2] = col[0] ^ col[1] ^ _gmul(col[2], 2) ^ _gmul(col[3], 3)
            state[4 * c + 3] = _gmul(col[0], 3) ^ col[1] ^ col[2] ^ _gmul(col[3], 2)

    add(0)
    for rnd in range(1, 10):
        sub()
        shift()
        mix()
        add(rnd)
    sub()
    shift()
    add(10)
    return bytes(state)

def _inc32(block: bytes) -> bytes:
    n = int.from_bytes(block[-4:], "big")
    return block[:-4] + ((n + 1) & 0xFFFFFFFF).to_bytes(4, "big")

def aes_ctr_xor(key: bytes, counter: bytes, data: bytes) -> bytes:
    out = b""
    block = counter
    for off in range(0, len(data), 16):
        stream = aes128_encrypt(block, key)
        chunk = data[off : off + 16]
        out += bytes(p ^ s for p, s in zip(chunk, stream))
        block = _inc32(block)
    return out

key = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c")
counter = bytes.fromhex("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
block = bytes.fromhex("6bc1bee22e409f96e93d7e117393172a")
cipher = aes_ctr_xor(key, counter, block)
assert cipher.hex() == "874d6191b620e3261bef6864990db6ce"
print(cipher.hex())

Where it is used

Counter mode is the keystream inside AES-GCM and the AES-CTR cipher suites used by IPsec and older TLS. The plaintext is xored with encrypted counters. GCM adds the tag that bare counter mode does not compute.


When you can drop this algorithm

Drop bare counter mode where a modified ciphertext must be rejected, and drop it where a counter might repeat under one key. Keep it as the encryption inside an authenticated mode that assigns each counter once.


Why this stays published

We publish this so a search for counter mode returns the encrypted counter and the NIST block. Counter mode encrypts successive counter blocks, xors them with the plaintext, and repeats the pad if a counter is reused.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *