Skip to main content

Encrypted fields

secure.Value[T] stores a value encrypted with AES-256-GCM, so a database dump or stolen backup reveals nothing. The column is text holding key:base64(nonce+ciphertext).

Store a value​

Set the keys once at startup. A key is 32 bytes (SetKeys returns an error otherwise). Its name is stored with every value, so keep names stable and free of colons.

type Patient struct {
ID int64
SSN secure.Value[string]
}

err := secure.SetKeys("2026", map[string][]byte{"2026": key})

patient := &Patient{SSN: secure.New("123-45-6789")}

err = db.Patients.Insert(ctx, patient)
// INSERT INTO "patients" ("ssn") VALUES ($1) RETURNING "id"
// -- $1 = '2026:<base64>'

loaded, err := db.Patients.Find(ctx, patient.ID)

fmt.Println(loaded.SSN.V) // 123-45-6789

fmt and JSON print [encrypted]. Read .V for the value. Decoding JSON fills it from a plain value, so a model with a secure field can come from a request body; the "[encrypted]" placeholder decodes as no change, so echoing a model back can't overwrite the value with it. ant.LogValues logs SQL arguments, so add .Sensitive() to the column to keep them out of logs (see security).

What can go inside​

T can be any type encoding/json handles, such as a struct or a slice, and it is sealed as JSON. A NULL column reads as the zero T.

secure.Value refuses text that isn't valid UTF-8, as a text column does. encoding/json would silently store U+FFFD in its place, so the write fails instead. To store arbitrary bytes, encode them first with base64 or hex.

Without SetKeys, reads and writes return secure.ErrNoKeys.

Search by a value​

A value encrypts differently every time, so ant.Eq and indexes can't find it. Store a keyed hash beside it, as a string since []byte isn't comparable.

type Patient struct {
ID int64
SSN secure.Value[string]
SSNHash string `ant:"unique"`
}

func blindIndex(value string) string {
mac := hmac.New(sha256.New, hashKey)
mac.Write([]byte(value))

return hex.EncodeToString(mac.Sum(nil))
}

var Patients = ant.Fields[Patient]()

patient := &Patient{SSN: secure.New(ssn), SSNHash: blindIndex(ssn)}

err := db.Patients.Insert(ctx, patient)

found, err := db.Patients.Where(ant.Eq(&Patients.SSNHash, blindIndex(ssn))).First(ctx)
// SELECT ... FROM "patients" WHERE "patients"."ssn_hash" = $1 LIMIT $2

The hash needs its own key. It reveals when two rows hold the same value, so use it only where that is acceptable. Update the hash whenever you change the value.

Rotate keys​

Add a new key and make it active. Old rows still read with the old key, since each value records its key. New writes use the new one.

err := secure.SetKeys("2027", map[string][]byte{"2027": newKey, "2026": oldKey})

To finish, rewrite the rows that still use the old key, then drop it. A row whose key is gone fails to read with secure.ErrUnknownKey, so check that none is left first. MarkModified makes SaveChanges write an unchanged row, and ChunkByKey keeps its place while the callback changes the rows it reads:

old := ant.SQLCond("ssn NOT LIKE ?", "2027:%")

err := db.Patients.Where(old).ChunkByKey(ctx, 500, func(batch []*Patient) error {
for _, p := range batch {
if err := ant.MarkModified(ctx, db, p); err != nil {
return err
}
}

return db.SaveChanges(ctx)
})
// SELECT ... FROM "patients" WHERE (ssn NOT LIKE $1) ORDER BY "patients"."id" LIMIT $2
// UPDATE "patients" SET "ssn" = $1, "ssn_hash" = $2 WHERE "patients"."id" = $3
left, err := db.Patients.Where(ant.SQLCond("ssn NOT LIKE ?", "2027:%")).Count(ctx)

secure.NeedsRotation(stored) does the same check on one stored string.

Limits​

  • A value isn't tied to its row, so someone who can write to the table can copy a ciphertext from one row to another.
  • Keys live in the process. Keep them in a secret store, never in the repository.
  • GCM with random nonces is safe for about four billion values per key. Rotate before then.
  • It protects data at rest. It doesn't protect against an application that is itself compromised.

The ledger example stores IBANs this way.