Skip to main content

Module encryption

Module encryption 

Source
Expand description

Attribute encryption for model columns: values are encrypted in Rust before they reach D1 and decrypted when rows are read, like Rails’ encrypts.

Keys are derived from SECRET_KEY_BASE with HKDF-SHA256 (separate from the session cookie key), and the cipher is AES-256-GCM, so a changed ciphertext fails to decrypt instead of giving a wrong value. A value is stored as text: v1: then the nonce and the ciphertext in URL-safe base64 (about 4/3 of the value plus 42 characters).

  • Encrypted: a random nonce per write. The same value never gives the same text twice, so the column cannot be searched.
  • Deterministic: the nonce comes from the value (HMAC-SHA256), so equal values give equal texts: WHERE email = ?1 and unique indexes work, at the price of revealing which rows share a value. Normalize before encrypting (e.g. lowercase an email) for case-insensitive lookups.

Both are field types for a model’s row struct: they deserialize by decrypting, bind as parameters by encrypting, and serialize to JSON as the plain value (see the Models guide, “Encrypted columns”).

§Keys and rotation

Ctx installs the keys the first time a Worker instance handles a request: one HKDF derivation, then pure Rust (AES-GCM of a short value costs microseconds of CPU). Values encrypted with a secret listed in SECRET_KEY_BASE_PREVIOUS still decrypt; writes use the current secret. Deterministic lookups must try every key during a rotation (Encryptor::deterministic_candidates with Query::is_in), until a job has rewritten the rows with the current key. Losing SECRET_KEY_BASE loses the data: back it up.

Structs§

Deterministic
A column encrypted deterministically: equal values give equal stored texts, so query().eq("email", Deterministic::from(email)) finds the row and a UNIQUE index works.
Encrypted
A column encrypted with a random nonce: reads decrypt, writes encrypt.
Encryptor
Encrypts and decrypts column values with keys derived from SECRET_KEY_BASE.

Functions§

install
Makes encryptor the one Encrypted and Deterministic use.
installed
The installed encryptor.
is_encrypted
Whether text looks like an encrypted value (starts with v1:).