How do you set up Active Record Encryption in a Rails 8.1 app to encrypt a patient's national ID column, and what does the database store?
answer
- one rake task prints three keys
- bin/rails db:encryption:init
- primary_key, deterministic_key, key_derivation_salt
- encrypts :national_id in the model
- JSON with p and h: iv, at
basics
~10 sRun bin/rails db:encryption:init, paste its primary_key, deterministic_key and key_derivation_salt under active_record_encryption in credentials, then declare encrypts :national_id. Rails stores a Base64 JSON envelope of ciphertext, IV and auth tag, and decrypts on read.
solid answer
~40 s`bin/rails db:encryption:init` prints three random values to paste into the target environment's credentials under `active_record_encryption`: `primary_key` (derives the key for ordinary, randomized encryption), `deterministic_key` (for `deterministic: true` attributes) and `key_derivation_salt` (salts the PBKDF2 derivation). Active Record's railtie reads them at boot. In the model, `encrypts :national_id` makes the attribute encrypt on write and decrypt on read with AES-256-GCM, so code keeps using `patient.national_id`. The column holds a JSON document such as `{"p":"...","h":{"iv":"...","at":"..."}}`: compressed, Base64-encoded ciphertext plus the IV and authentication tag, so string columns need room for the overhead. The attribute is also added to `filter_parameters` and shows as `[FILTERED]` in `inspect`. A missing key raises `ActiveRecord::Encryption::Errors::Configuration` when the attribute is used.
code
ruby · 9 linesclass Patient < ApplicationRecord
encrypts :national_id
end
patient = Patient.create!(name: "R. Osei", national_id: "AB123456C")
patient.national_id # => "AB123456C"
patient.encrypted_attribute?(:national_id) # => true
patient.ciphertext_for(:national_id)
# => "{\"p\":\"n7J...\",\"h\":{\"iv\":\"3nr...\",\"at\":\"JBs...\"}}"go deeper
Recall db:encryption:init, the three keys, putting them in credentials, and declaring encrypts on the attribute.
Explain what each key is for, the JSON envelope, AES-256-GCM with a random IV, and why columns need extra length.
Plan rollout: keys per environment, column sizes, filtering, and what happens to rows that are still plain text.
Decide which fields justify application-level encryption against the cost in queries, storage and key management.
## What Active Record Encryption is **Active Record Encryption** encrypts chosen model attributes in the application before they are written, and decrypts them when records are loaded. The database only ever sees ciphertext for those columns. It is built into Rails, configured with three secrets, and switched on per attribute with the `encrypts` macro. ## Step 1: generate the keys ```bash bin/rails db:encryption:init ``` The task prints a block to paste into the **credentials of the target environment**: ```yaml active_record_encryption: primary_key: <32 random characters> deterministic_key: <32 random characters> key_derivation_salt: <32 random characters> ``` What each one does: - **`primary_key`** is the password from which Rails derives the encryption key for ordinary, randomized encryption. It may be a list, which is how rotation works. - **`deterministic_key`** is the single password used for attributes declared `deterministic: true`. - **`key_derivation_salt`** salts the PBKDF2 derivation that turns those passwords into 256-bit keys; since `load_defaults 7.1` the derivation uses SHA-256. Active Record's railtie reads the three values from `Rails.application.credentials` when encryption loads. If a needed one is absent, using an encrypted attribute raises `ActiveRecord::Encryption::Errors::Configuration` with a message naming the missing credential. ## Step 2: declare the attribute ```ruby class Patient < ApplicationRecord encrypts :national_id end ``` From then on `Patient.create!(national_id: "AB123456C")` encrypts before the `INSERT`, and `patient.national_id` returns plain text. Nothing else in the code changes. `encrypts` accepts several names at once and options such as `deterministic:`, `downcase:`, `ignore_case:`, `previous:` and `support_unencrypted_data:`. ## What the column holds Each value is stored as a small JSON document: | Key | Meaning | |---|---| | `p` | the payload: ciphertext, compressed by default and Base64-encoded | | `h.iv` | the initialization vector used for this value | | `h.at` | the GCM authentication tag, which detects tampering | The cipher is **AES-256-GCM**. By default each write uses a random IV, so the same national ID saved twice produces two different ciphertexts. A `nil` stays `NULL`; it is not encrypted. ## Storage considerations Because of the JSON envelope and Base64, an encrypted value is larger than the original. The Rails guide estimates a worst-case overhead of about 255 bytes and suggests, for example, `string(510)` where `string(255)` held an email address. `config.active_record.encryption.validate_column_size` (on by default) adds a length validation from the column's limit. Plan the column type before encrypting, and use `text` for long content. ## What you get for free - **Log filtering**: with `add_to_filter_parameters` (default true), each encrypted attribute is added to `config.filter_parameters`, so request logs show `[FILTERED]`. - **Console and inspect filtering**: the attribute is added to the model's `filter_attributes`, so `Patient.first` shows `national_id: "[FILTERED]"`. - **Inspection helpers**: `patient.encrypted_attribute?(:national_id)` and `patient.ciphertext_for(:national_id)` help when debugging. ## Common mistakes 1. Pasting the keys into the development credentials only, then deploying to production without them. 2. Encrypting an existing column that already holds plain text without a migration plan: reads of old rows raise `ActiveRecord::Encryption::Errors::Decryption` by default. 3. Keeping a `string(20)` column for a value whose ciphertext needs hundreds of characters. 4. Expecting `where(national_id: ...)` to work on a randomized attribute; lookups need deterministic encryption. ## What interviewers check - That you know the task, the three keys and where they live. - That `encrypts` is transparent to application code. - That you understand what the column stores and its size impact.
- Why does saving the same national ID on two patients produce different ciphertexts?`encrypts` is non-deterministic by default: each write uses a fresh random IV with AES-256-GCM, so equal plaintexts give unequal ciphertexts. That hides which rows share a value, but it also means the database cannot compare them, so `where(national_id: ...)` finds nothing. Only `deterministic: true` derives the IV from the plaintext.
- Can the keys come from somewhere other than credentials?Yes. `config.active_record.encryption.primary_key`, `deterministic_key` and `key_derivation_salt` can be set in configuration, for instance from environment variables. The guide recommends credentials and warns never to commit the values in plain configuration.
- encrypts needs a separate *_encrypted column beside the original.
- bin/rails db:encryption:init writes the keys into credentials for you.
- Encrypted values fit in the same string length as the plain values.
- Active Record Encryption derives its keys from secret_key_base.
- A nil national ID is stored as an encrypted empty value.