Articles / Cryptography

  • cryptography
  • aes-gcm
  • key-commitment
  • aead
  • go
  • security

Why One GCM Tag Check Cannot Tell You Which Key Was Used

You can build an AES-GCM ciphertext that decrypts without error under two different keys. Same bytes, same nonce, same tag, two successful calls to Open, two different plaintexts.

Nothing is broken in AES, and your library has no bug. GCM promises that someone without the key cannot forge a message. It promises nothing about someone who holds the keys and wants one message to fit both. The missing property is called key commitment.

The tag is a polynomial, and polynomials can be solved

GCM's authentication tag is mostly arithmetic in a finite field, GF(2^128). With a 96-bit nonce, no associated data and two ciphertext blocks C1 and C2, it looks like this:

tag = C1*H^3 + C2*H^2 + L*H + mask
  • H is the all-zero block encrypted under your key.
  • mask is a counter block built from the nonce, also encrypted under your key.
  • L encodes the lengths.
  • Addition is XOR.

Now take two keys. Each gives its own H and mask. We want both equations to produce the same tag, so set them equal. Pick C1 freely, and the only unknown left is C2.

It appears only to the first power. One field division gives you the colliding block: no search, no luck, no enormous compute bill.

Quick detour, because this bit is lovely. In this field, adding and subtracting are the same operation, and squaring distributes over addition. So the thing we divide by, H1^2 + H2^2, equals (H1 + H2)^2. It is zero only if the two values of H match, which for two random keys is not going to happen.

Eighty-odd lines of Go make it happen

The standard library does not expose GHASH, so the program below carries its own field multiplication, following NIST SP 800-38D. It is slow and not constant time, which is fine for a demonstration and unfit for anything else. The final check uses the ordinary crypto/cipher GCM.

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/binary"
	"fmt"
	"log"
)

// elem is an element of GF(2^128) in GCM's bit order.
type elem struct{ hi, lo uint64 }

func load(b []byte) elem {
	return elem{binary.BigEndian.Uint64(b[:8]), binary.BigEndian.Uint64(b[8:16])}
}

func (a elem) bytes() []byte {
	return binary.BigEndian.AppendUint64(binary.BigEndian.AppendUint64(nil, a.hi), a.lo)
}

func (a elem) add(b elem) elem { return elem{a.hi ^ b.hi, a.lo ^ b.lo} }

// mul is the bit-by-bit algorithm from NIST SP 800-38D. Not constant time.
func (a elem) mul(b elem) elem {
	var z elem
	for i := range 128 {
		word := a.hi
		if i >= 64 {
			word = a.lo
		}
		if word>>(63-i%64)&1 == 1 {
			z = z.add(b)
		}
		carry := b.lo & 1
		b.lo = b.lo>>1 | b.hi<<63
		b.hi = b.hi>>1 ^ carry*0xe100000000000000
	}
	return z
}

// inv computes a^(2^128-2), which is 1/a for any non-zero a.
func (a elem) inv() elem {
	r := elem{hi: 1 << 63} // the number one, in GCM's bit order
	for range 127 {
		a = a.mul(a)
		r = r.mul(a)
	}
	return r
}

// secrets returns the GHASH key H and the tag mask for one key and nonce.
func secrets(b cipher.Block, nonce []byte) (h, mask elem) {
	var in, out [16]byte
	b.Encrypt(out[:], in[:])
	h = load(out[:])
	copy(in[:], nonce)
	in[15] = 1
	b.Encrypt(out[:], in[:])
	return h, load(out[:])
}

// collide returns ciphertext||tag that opens under both keys. The first
// 16 bytes decrypt to msg under k1; the second block is solved for.
func collide(k1, k2, nonce, msg []byte) ([]byte, error) {
	b1, err := aes.NewCipher(k1)
	if err != nil {
		return nil, err
	}
	b2, err := aes.NewCipher(k2)
	if err != nil {
		return nil, err
	}
	g1, err := cipher.NewGCM(b1)
	if err != nil {
		return nil, err
	}
	c1 := g1.Seal(nil, nonce, msg[:16], nil)[:16]

	h1, s1 := secrets(b1, nonce)
	h2, s2 := secrets(b2, nonce)
	length := elem{lo: 32 * 8} // no AAD, 32 bytes of ciphertext

	// tag = c1*H^3 + x*H^2 + length*H + mask
	rest := func(h, mask elem) elem {
		return load(c1).mul(h).mul(h).mul(h).add(length.mul(h)).add(mask)
	}
	// Set both tags equal and solve the linear equation for x.
	x := rest(h1, s1).add(rest(h2, s2)).mul(h1.mul(h1).add(h2.mul(h2)).inv())
	tag := rest(h1, s1).add(x.mul(h1).mul(h1))

	out := append(c1, x.bytes()...)
	return append(out, tag.bytes()...), nil
}

func main() {
	k1 := []byte("first key, 32 bytes long, aaaaaa")
	k2 := []byte("other key, 32 bytes long, bbbbbb")
	nonce := make([]byte, 12)

	sealed, err := collide(k1, k2, nonce, []byte("Pay Alice GBP 10"))
	if err != nil {
		log.Fatal(err)
	}
	for _, k := range [][]byte{k1, k2} {
		b, err := aes.NewCipher(k)
		if err != nil {
			log.Fatal(err)
		}
		g, err := cipher.NewGCM(b)
		if err != nil {
			log.Fatal(err)
		}
		pt, err := g.Open(nil, nonce, sealed, nil)
		fmt.Printf("err=%v plaintext=%q\n", err, pt)
	}
}

Run it and both opens succeed:

err=<nil> plaintext="Pay Alice GBP 10g\xef\x06\xf2S\xfe<5\x94g'\t\x1bw)U"
err=<nil> plaintext="\xea\xf0\xee~ɧ,\xad\xfb>\xb9u\xb3\xe1/\xac\xda\xf9\xf8\xcc%\x9e\xa8\x03v\xfb\xf7\xeb\x1b"

Junk plaintext is less of a defence than it looks

The first key yields our message followed by 16 bytes of noise. The second yields noise throughout. You might reasonably say that any sane parser would reject that.

Some will. But many file formats tolerate junk, ignoring trailing bytes or letting a header skip over a region. Albertini and colleagues built a tool producing AES-GCM ciphertexts that decrypt to two valid files, across formats including PDF, Windows executables and DICOM.

Associated data does not save you either. Someone who knows both keys can include its contribution in both equations and solve as before. That applies to a key ID placed in the AAD too.

Three places where "it opened, so it was this key" goes wrong

Abuse reports can point at the wrong content

In Fast Message Franking: From Invisible Salamanders to Encryptment, Dodis, Grubbs, Ristenpart and Woodage attacked Facebook Messenger's scheme for reporting abusive attachments, which used AES-GCM. A malicious sender could deliver an objectionable image that the recipient could not report.

The same shape worries me in any multi-recipient design. If one ciphertext is shared and keys are handed out individually, a dishonest sender can show different people different content.

A yes or no answer can leak a password

Suppose a server derives a key from a password and reveals whether decryption worked, even through timing or behaviour. An attacker can extend the trick above from two keys to many, at a cost of roughly one extra solved block per key.

They craft one message valid under a whole batch of candidate passwords. A rejection rules out the batch. An acceptance means the password is inside it, so they split the batch and ask again.

This is a partitioning oracle attack, described by Len, Grubbs and Ristenpart. They used it to recover passwords from Shadowsocks proxy servers. It is not only a GCM problem: ChaCha20-Poly1305 was among the schemes they attacked.

Key rotation by trial and error picks whoever answers first

Plenty of code loops over a key ring and keeps the first key whose Open succeeds. For honestly produced messages this works, because an accidental match is astronomically unlikely.

For a crafted message, the order of your loop decides the plaintext. Two services holding the same ring in different orders can disagree about what one message says. A key ID tells them where to look, but unless something binds the ciphertext to that key, a creator who knows two keys can still make either ID work.

Check a commitment before you open anything

The sturdy fix is to publish a value that only one key can plausibly produce, and verify it first. Here HKDF-SHA256 turns a master key and a random salt into 64 bytes: half encrypts, half is the commitment. Finding two master keys with the same commitment should mean finding a hash collision.

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/hkdf"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"errors"
	"fmt"
	"log"
)

var errOpen = errors.New("message could not be opened")

// derive splits a 32-byte master key into an AEAD and a commitment value.
func derive(master, salt []byte) (cipher.AEAD, []byte, error) {
	if len(master) != 32 {
		return nil, nil, errors.New("master key must be 32 random bytes")
	}
	okm, err := hkdf.Key(sha256.New, master, salt, "example.com/committing-gcm/v1", 64)
	if err != nil {
		return nil, nil, err
	}
	block, err := aes.NewCipher(okm[:32])
	if err != nil {
		return nil, nil, err
	}
	aead, err := cipher.NewGCM(block)
	if err != nil {
		return nil, nil, err
	}
	return aead, okm[32:], nil
}

// Seal returns salt || commitment || ciphertext || tag.
func Seal(master, plaintext, aad []byte) ([]byte, error) {
	salt := make([]byte, 32)
	rand.Read(salt)
	aead, commit, err := derive(master, salt)
	if err != nil {
		return nil, err
	}
	// A fixed nonce is safe only because each fresh salt gives a fresh key.
	nonce := make([]byte, aead.NonceSize())
	return aead.Seal(append(salt, commit...), nonce, plaintext, aad), nil
}

func Open(master, sealed, aad []byte) ([]byte, error) {
	if len(sealed) < 64 {
		return nil, errOpen
	}
	aead, commit, err := derive(master, sealed[:32])
	if err != nil {
		return nil, err
	}
	if !hmac.Equal(commit, sealed[32:64]) {
		return nil, errOpen
	}
	pt, err := aead.Open(nil, make([]byte, aead.NonceSize()), sealed[64:], aad)
	if err != nil {
		return nil, errOpen
	}
	return pt, nil
}

func main() {
	k1, k2 := make([]byte, 32), make([]byte, 32)
	rand.Read(k1)
	rand.Read(k2)
	s, err := Seal(k1, []byte("hello"), nil)
	if err != nil {
		log.Fatal(err)
	}
	for _, k := range [][]byte{k1, k2} {
		pt, err := Open(k, s, nil)
		fmt.Printf("%q %v\n", pt, err)
	}
}

This needs Go 1.24 or later for crypto/hkdf. It prints "hello" <nil> for the right key and an error for the other. The cost is 64 bytes per message and a little key derivation.

What this fix does not cover

Key commitment is a narrow promise, so check it is the one you need:

  • It binds the ciphertext to a key. It does not promise that one key holder cannot find a second nonce or associated data that also fits. RFC 9771 distinguishes key commitment from the stronger full commitment.
  • It does not make passwords safe as master keys. Run them through a slow password KDF such as Argon2id first, and remember that a stored commitment lets anyone holding it test guesses offline.
  • It does not say who sent the message. Everyone with the key can still produce it. Use a signature if authorship matters.
  • It is a new message format. Old ciphertexts stay uncommitted until re-encrypted, and a fallback to the old path hands the attacker their old options.

You may also see a padding fix: prefix the plaintext with zeros and reject anything that does not decrypt with them intact. The Albertini paper notes that this kind of simple fix needs analysis for each scheme. The pad length sets your security margin, and a single 16-byte block leaves a birthday-style search of about 2^64, so do not improvise it.

If you use an encryption library instead of raw GCM, look for the words "key commitment" in its documentation. "Authenticated encryption" on its own does not tell you, and the gap only shows up when somebody with two keys goes looking for it.