{"id":488,"date":"2026-11-13T13:39:25","date_gmt":"2026-11-13T05:39:25","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-counter-mode-turns-aes-into-a-keystream\/"},"modified":"2026-11-13T21:58:52","modified_gmt":"2026-11-13T13:58:52","slug":"how-counter-mode-turns-aes-into-a-keystream","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-counter-mode-turns-aes-into-a-keystream\/","title":{"rendered":"How counter mode turns AES into a keystream"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Counter mode<\/strong> 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 <code>2^32<\/code> 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Choose a counter block that will not repeat under the same key.<\/li>\n<li>Encrypt the counter with the block cipher.<\/li>\n<li>Xor the keystream with the next plaintext bytes.<\/li>\n<li>Increment the last four bytes and repeat until the message is consumed.<\/li>\n<\/ol>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when a counter is repeated<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Restart the same counter for a second message<\/td>\n<td>The pad repeats. The xor of the ciphertexts is the xor of the plaintexts.<\/td>\n<\/tr>\n<tr>\n<td>Increment the whole 16-byte block as if it were little-endian<\/td>\n<td>This NIST counter increments the last four bytes as a big-endian integer. A different increment is a different keystream.<\/td>\n<\/tr>\n<tr>\n<td>Encrypt the plaintext and then xor the counter<\/td>\n<td>Counter mode encrypts the counter. The plaintext meets the cipher only at the xor.<\/td>\n<\/tr>\n<tr>\n<td>Rely on the xor to detect a modified ciphertext<\/td>\n<td>A flipped bit decrypts to a flipped bit. A tag is a separate check.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">GCM is counter mode plus GHASH. The fragment is the counter keystream.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment encrypts the NIST SP 800-38A counter block and xors it with one plaintext block. It prints <code>874d6191b620e3261bef6864990db6ce<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def _xtime(a: int) -&gt; int:\n    return ((a &lt;&lt; 1) ^ 0x1B) &amp; 0xFF if a &amp; 0x80 else (a &lt;&lt; 1) &amp; 0xFF\n\ndef _gmul(a: int, b: int) -&gt; int:\n    p = 0\n    for _ in range(8):\n        if b &amp; 1:\n            p ^= a\n        a = _xtime(a)\n        b &gt;&gt;= 1\n    return p\n\ndef _sbox() -&gt; list[int]:\n    box = []\n    for x in range(256):\n        inv = 0 if x == 0 else next(i for i in range(1, 256) if _gmul(x, i) == 1)\n        y = 0\n        for i in range(8):\n            bit = (inv &gt;&gt; i) ^ (inv &gt;&gt; ((i + 4) % 8)) ^ (inv &gt;&gt; ((i + 5) % 8))\n            bit ^= (inv &gt;&gt; ((i + 6) % 8)) ^ (inv &gt;&gt; ((i + 7) % 8)) ^ (0x63 &gt;&gt; i)\n            y |= (bit &amp; 1) &lt;&lt; i\n        box.append(y)\n    return box\n\n_S = _sbox()\n\ndef aes128_encrypt(block: bytes, key: bytes) -&gt; bytes:\n    words = list(key)\n    rcon = 1\n    while len(words) &lt; 176:\n        t = words[-4:]\n        if len(words) % 16 == 0:\n            t = t[1:] + t[:1]\n            t = [_S[b] for b in t]\n            t[0] ^= rcon\n            rcon = _xtime(rcon)\n        earlier = words[-16:-12]\n        words.extend(earlier[i] ^ t[i] for i in range(4))\n    state = list(block)\n\n    def add(rnd: int) -&gt; None:\n        rk = words[rnd * 16 : (rnd + 1) * 16]\n        for i in range(16):\n            state[i] ^= rk[i]\n\n    def sub() -&gt; None:\n        for i in range(16):\n            state[i] = _S[state[i]]\n\n    def shift() -&gt; None:\n        for r in range(1, 4):\n            row = [state[r + 4 * c] for c in range(4)]\n            row = row[r:] + row[:r]\n            for c in range(4):\n                state[r + 4 * c] = row[c]\n\n    def mix() -&gt; None:\n        for c in range(4):\n            col = state[4 * c : 4 * c + 4]\n            state[4 * c] = _gmul(col[0], 2) ^ _gmul(col[1], 3) ^ col[2] ^ col[3]\n            state[4 * c + 1] = col[0] ^ _gmul(col[1], 2) ^ _gmul(col[2], 3) ^ col[3]\n            state[4 * c + 2] = col[0] ^ col[1] ^ _gmul(col[2], 2) ^ _gmul(col[3], 3)\n            state[4 * c + 3] = _gmul(col[0], 3) ^ col[1] ^ col[2] ^ _gmul(col[3], 2)\n\n    add(0)\n    for rnd in range(1, 10):\n        sub()\n        shift()\n        mix()\n        add(rnd)\n    sub()\n    shift()\n    add(10)\n    return bytes(state)\n\ndef _inc32(block: bytes) -&gt; bytes:\n    n = int.from_bytes(block[-4:], &quot;big&quot;)\n    return block[:-4] + ((n + 1) &amp; 0xFFFFFFFF).to_bytes(4, &quot;big&quot;)\n\ndef aes_ctr_xor(key: bytes, counter: bytes, data: bytes) -&gt; bytes:\n    out = b&quot;&quot;\n    block = counter\n    for off in range(0, len(data), 16):\n        stream = aes128_encrypt(block, key)\n        chunk = data[off : off + 16]\n        out += bytes(p ^ s for p, s in zip(chunk, stream))\n        block = _inc32(block)\n    return out\n\nkey = bytes.fromhex(&quot;2b7e151628aed2a6abf7158809cf4f3c&quot;)\ncounter = bytes.fromhex(&quot;f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff&quot;)\nblock = bytes.fromhex(&quot;6bc1bee22e409f96e93d7e117393172a&quot;)\ncipher = aes_ctr_xor(key, counter, block)\nassert cipher.hex() == &quot;874d6191b620e3261bef6864990db6ce&quot;\nprint(cipher.hex())\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Counter mode is the keystream inside <strong>AES-GCM<\/strong> 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for counter mode returns the encrypted counter and the NIST block. <strong>Counter mode encrypts successive counter blocks, xors them with the plaintext, and repeats the pad if a counter is reused.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,49],"tags":[],"class_list":["post-488","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-cryptography"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/488","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=488"}],"version-history":[{"count":1,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/488\/revisions"}],"predecessor-version":[{"id":700,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/488\/revisions\/700"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=488"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=488"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=488"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}