Secrets, cryptography and supply chain · 5 MIN READ

Encrypt records with AES-GCM: random nonces, a key ID, and the record ID as additional data

Seal application records with AES-GCM so that tampering, row swapping and key rotation are handled explicitly, and explain why a repeated nonce breaks GCM.

Encrypting a column protects data in backups, replicas and database dumps, but only if the record format answers more than which key to use. The crypto-purposes lesson explains why encryption must be authenticated. This lesson builds the record envelope: AES-GCM through crypto/cipher, a fresh random nonce per seal, a key ID that survives rotation, and additional data that ties each ciphertext to the row it belongs to.

security · A MAP OF THE IDEA

  1. Pick the current key ID
  2. Seal with a random nonce
  3. Bind header + record ID
  4. Rotate, re-encrypt, retire

Useful when

  • Tampering, row swaps and wrong keys all fail with one authentication error.
  • Key IDs turn rotation into a gradual migration instead of a flag day.

Watch out

  • A repeated nonce under one key breaks both confidentiality and integrity.
  • Ciphertext length reveals plaintext length, and encrypted columns are not searchable.

Implementation & operation cost: 33 bytes per record, one AES-GCM operation per read and write, and a re-encryption job plus a key inventory for every rotation.

01

What a record envelope must guarantee

Picture customers' bank details stored encrypted in a table, and three attackers. One reads a backup and should learn nothing but lengths. One flips bits in a ciphertext, hoping to change a value without knowing it. One can write to the database, perhaps through a bug elsewhere, and copies the ciphertext from their own row into a victim's row, so that the victim's next payout goes to the attacker's account. AES-GCM, an AEAD, handles the first two: it hides the plaintext, and its tag check rejects any modification. The third needs context. Passing the record ID as additional data, which is authenticated but not encrypted, means a ciphertext opens only in the row it was sealed for.

02

Seal, open, rotate and fail

The envelope is version(1) || keyID(4) || nonce(12) || ciphertext || tag(16). cipher.NewGCMWithRandomNonce, added in Go 1.24, draws the nonce from crypto/rand and prepends it, so the caller cannot pass a stale one. The header and the record ID together form the additional data. The program prints sizes, booleans and errors rather than ciphertext, so its output is identical on every run even though keys and nonces are random.

go
package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/binary"
	"errors"
	"fmt"
)

const version = 1

// Keyring maps a key ID to an AEAD. Sealed records carry the ID that
// encrypted them, so old records stay readable after rotation.
type Keyring struct {
	current uint32
	aeads   map[uint32]cipher.AEAD
}

func (k *Keyring) Add(id uint32, key []byte) error {
	block, err := aes.NewCipher(key) // 32-byte key: AES-256
	if err != nil {
		return err
	}
	aead, err := cipher.NewGCMWithRandomNonce(block) // nonce generated and prepended for us
	if err != nil {
		return err
	}
	k.aeads[id], k.current = aead, id
	return nil
}

// header is version(1) || keyID(4). It is authenticated together with the
// record ID, so neither can be changed without failing Open.
func additionalData(header []byte, recordID string) []byte {
	return append(bytes.Clone(header), recordID...)
}

func (k *Keyring) Seal(recordID string, plaintext []byte) []byte {
	header := binary.BigEndian.AppendUint32([]byte{version}, k.current)
	return k.aeads[k.current].Seal(header, nil, plaintext, additionalData(header, recordID))
}

func (k *Keyring) Open(recordID string, blob []byte) ([]byte, error) {
	if len(blob) < 5 || blob[0] != version {
		return nil, errors.New("unsupported record format")
	}
	id := binary.BigEndian.Uint32(blob[1:5])
	aead, ok := k.aeads[id]
	if !ok {
		return nil, fmt.Errorf("unknown key ID %d", id)
	}
	return aead.Open(nil, nil, blob[5:], additionalData(blob[:5], recordID))
}

func newKey() []byte {
	key := make([]byte, 32)
	rand.Read(key) // never fails; crashes the program if the OS source does
	return key
}

func must[T any](v T, err error) T {
	if err != nil {
		panic(err)
	}
	return v
}

func main() {
	ring := &Keyring{aeads: map[uint32]cipher.AEAD{}}
	if err := ring.Add(1, newKey()); err != nil {
		panic(err)
	}
	pii := []byte(`{"iban":"DE89370400440532013000"}`)
	blob := ring.Seal("customer-17", pii)
	fmt.Printf("plaintext %d bytes, sealed %d bytes\n", len(pii), len(blob))
	fmt.Println("two seals differ:", !bytes.Equal(blob, ring.Seal("customer-17", pii)))

	got, err := ring.Open("customer-17", blob)
	fmt.Println("open own row:", string(got), err)
	_, err = ring.Open("customer-99", blob)
	fmt.Println("open copied to another row:", err)

	tampered := bytes.Clone(blob)
	tampered[len(tampered)-20] ^= 0x01
	_, err = ring.Open("customer-17", tampered)
	fmt.Println("open after one flipped bit:", err)

	if err := ring.Add(2, newKey()); err != nil { // rotate: new writes use key 2
		panic(err)
	}
	fresh := ring.Seal("customer-18", pii)
	_, err = ring.Open("customer-17", blob)
	fmt.Println("new record key ID:", binary.BigEndian.Uint32(fresh[1:5]), "old record still opens:", err == nil)
	delete(ring.aeads, 1) // retiring a key before re-encrypting its rows
	_, err = ring.Open("customer-17", blob)
	fmt.Println("after retiring key 1:", err)

	// TEST PATH ONLY: a fixed nonce, to show why nonces must never repeat.
	block := must(aes.NewCipher(newKey()))
	gcm := must(cipher.NewGCM(block))
	fixedNonce := make([]byte, gcm.NonceSize())
	p1, p2 := []byte("transfer 100 to acct 1111"), []byte("transfer 900 to acct 6666")
	c1 := gcm.Seal(nil, fixedNonce, p1, nil)
	c2 := gcm.Seal(nil, fixedNonce, p2, nil)
	recovered := make([]byte, len(p1))
	for i := range recovered { // an observer who knows p1 learns p2
		recovered[i] = c1[i] ^ c2[i] ^ p1[i]
	}
	fmt.Printf("nonce reuse recovers: %s\n", recovered)
}
Read the code

The 33-byte plaintext becomes 66 bytes: 5 of header, 12 of nonce and 16 of tag. Two seals of the same value differ because each draws a new nonce. Opening under customer-99 fails with cipher: message authentication failed, the same error as a flipped bit; GCM cannot say which part was wrong, and should not. additionalData clones the header before appending, so the append cannot write into the buffer Seal is about to fill. After key 2 is added, new records carry key ID 2 while the old record still opens with key 1, and deleting key 1 too early makes it unreadable. The final block is a labeled test path: cipher.NewGCM with a fixed all-zero nonce. Two messages sealed under one nonce let anyone who knows the first recover the second with XOR.

03

Nonces must never repeat under one key

GCM is counter mode plus a polynomial MAC. Reusing a nonce under the same key reuses the keystream, so the XOR of two ciphertexts equals the XOR of their plaintexts, as the test path shows. Worse, two messages under one nonce let an attacker solve for the authentication subkey and forge valid tags for messages of their choosing. A random 96-bit nonce keeps collisions negligible only within a budget: the NewGCMWithRandomNonce documentation says a key must not encrypt more than 2^32 messages. Counters avoid randomness but are hard to keep unique across replicas, restarts and restored backups. For very high volumes per key, rotate by message count or time, derive separate keys per tenant, or use XChaCha20-Poly1305 from golang.org/x/crypto/chacha20poly1305, whose 192-bit nonces can be chosen at random for far more messages.

04

Rotation is a data migration, not a config change

A key ID in every record is what makes rotation possible: readers choose the key from the record and writers always use the current key. Rotation then has three phases. Add the new key everywhere and make it current. Re-encrypt old rows in a background job that opens and reseals each one. Retire the old key only when a count of rows by key ID reaches zero; retiring first, as the program shows, turns rotation into data loss. In production the keys usually come from a key management service through envelope encryption: a master key held by the service encrypts the data keys your application uses, so rotating the master key re-wraps a few small data keys instead of rewriting every row. The key ID is not secret, but it is authenticated through the additional data, so editing it in place fails the tag check.

05

Limits and the review checklist

An AEAD hides content, not size: here the ciphertext is always 33 bytes longer than the plaintext, so pad values whose length is sensitive. Encrypted columns cannot be searched or indexed; if you need equality lookups, store a separate HMAC of the normalized value under a different key, accepting that it reveals which rows are equal. Additional data must be unambiguous: when it combines several variable-length fields, length-prefix each one so that (ab, c) and (a, bc) differ. On an authentication failure, return an error and raise an alert; never log ciphertext next to plaintext, and never fall back to returning unauthenticated bytes. Tests should flip every byte of a sealed record, move it to another ID, open it after rotation and after retirement, and assert that a configured key is exactly 32 bytes.

TAKE THIS WITH YOU

Use an AEAD with a fresh random nonce per seal, authenticate a versioned header and the record ID as additional data, carry a key ID for rotation, and retire a key only after no record uses it.

Check your understanding

An attacker with database write access copies their own encrypted bank details into a victim's row. What stops the application from accepting them?

Go to the source

Progress stays in this browser. No account needed.