How GCM authenticates ciphertext with GHASH

Short answer: GCM encrypts with counter mode and authenticates with GHASH. H is the AES encryption of the zero block. For a 12-byte nonce, J0 is the nonce followed by 00000001. Encryption starts at the next counter. GHASH multiplies each ciphertext block by H in GF(2^128). The last field element carries the bit lengths of the additional data and the ciphertext. The tag is GHASH xored with the encryption of J0.


What the problem actually asks

Counter mode hides a message and does not detect a change. GCM adds a tag so a receiver can reject a ciphertext that was not produced with the key. The additional authenticated data is covered by the tag and is not encrypted. The fragment uses an empty additional-data string and a 12-byte nonce, which is the usual nonce length. A nonce under one key is used once. Repeating it repeats the counter keystream and breaks the authenticator. The fragment does not show how to exploit that repeat. It shows the tag.


What the algorithm guarantees

A receiver who recomputes the tag and compares it in full accepts only a ciphertext whose GHASH matches. The comparison has to be the whole tag. Encryption is counter mode, so confidentiality still depends on unique counters. The field multiplication uses the GCM polynomial, with the reduction constant 0xe1 followed by 120 zero bits in the bit ordering the implementation shifts. An empty message still has a tag, because the length block is hashed.


The working steps

  1. Encrypt the zero block to obtain H.
  2. Form J0 as the 12-byte nonce followed by 00000001.
  3. Encrypt the successive counters, starting at J0 + 1, and xor them with the plaintext.
  4. Hash the additional data, the ciphertext, and the two length fields by multiplying by H.
  5. Xor the hash with the encryption of J0 to obtain the tag.

Approaches that look simpler and fail

Approach Why it fails when a nonce is repeated under one key
Reuse a nonce for a second message The counter keystream repeats, and the authenticator is no longer binding. Each nonce is used once.
Compare only the first few tag bytes The check is the whole tag. A shortened comparison is a different check.
Hash the plaintext instead of the ciphertext GHASH covers the ciphertext and the additional data. Hashing the plaintext is a different authenticator.
Build J0 by appending the counter for a nonce that is not 12 bytes The fragment defines J0 for a 12-byte nonce. Other lengths hash the nonce first.

CBC and bare counter mode leave the ciphertext unauthenticated. GCM is the authenticated combination.


A working example

This Python fragment encrypts hello under the all-zero AES-128 key and a 12-byte zero nonce, then computes the GHASH tag. It prints 6bedb6a20f fc05f3475d29034caa1cc8fa3628c39f.

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 _ghash_mul(x: int, y: int) -> int:
    z = 0
    for i in range(128):
        if (x >> (127 - i)) & 1:
            z ^= y
        if y & 1:
            y = (y >> 1) ^ 0xE1000000000000000000000000000000
        else:
            y >>= 1
    return z

def aes_gcm(key: bytes, iv: bytes, plaintext: bytes, aad: bytes = b"") -> tuple[bytes, bytes]:
    h = int.from_bytes(aes128_encrypt(b"\x00" * 16, key), "big")
    if len(iv) == 12:
        j0 = iv + b"\x00\x00\x00\x01"
    else:
        raise ValueError("this example uses a 96-bit nonce")
    counter = _inc32(j0)
    stream = b""
    while len(stream) < len(plaintext):
        stream += aes128_encrypt(counter, key)
        counter = _inc32(counter)
    ct = bytes(p ^ s for p, s in zip(plaintext, stream))

    def blocks(buf: bytes) -> list[int]:
        if not buf:
            return []
        buf += b"\x00" * ((16 - len(buf) % 16) % 16)
        return [int.from_bytes(buf[i : i + 16], "big") for i in range(0, len(buf), 16)]

    y = 0
    for block in blocks(aad) + blocks(ct):
        y = _ghash_mul(y ^ block, h)
    lengths = (len(aad) * 8 << 64) | (len(ct) * 8)
    y = _ghash_mul(y ^ lengths, h)
    tag = (y ^ int.from_bytes(aes128_encrypt(j0, key), "big")).to_bytes(16, "big")
    return ct, tag

key, iv, text = bytes(16), bytes(12), b"hello"
cipher, tag = aes_gcm(key, iv, text)
assert cipher.hex() == "6bedb6a20f" and tag.hex() == "fc05f3475d29034caa1cc8fa3628c39f"
print(cipher.hex(), tag.hex())

Where it is used

TLS 1.3 and IPsec authenticate ciphertext with AES-GCM. HTTPS on a current browser is usually this mode: counter-mode encryption plus a GHASH tag. A nonce under one key is used once.


When you can drop this algorithm

Drop GCM where a nonce might be reused under one key. Keep it where the implementation stores enough state, or draws a large enough random nonce, that each nonce occurs once.


Why this stays published

We publish this so a search for GCM returns GHASH, the 96-bit nonce layout, and the tag. GCM encrypts with a counter that starts just after the nonce block and tags the ciphertext by multiplying by the encryption of the zero block.

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

Leave a Reply

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