All posts

Rails db encryption cheatsheet

A few notes to refer to when needing to add database encryption to a Rails app that uses ActiveRecord:

*This is not a comprehensive post. It is a quick reference if you have some experience with Rails but haven’t used it recently.

  1. Install a third party gem, attr_encrypted
gem install attr_encrypted
  1. Generate a migration to add the encrypted column name. You must prefix the column name with “encrypted”.
rails g migration add_secret_to_users encrypted_secret
  1. Add the method attr_encrypted to your ActiveRecord model, the first argument is your column name without the encrypted prefix. They key option will be the key used to handle the actual encryption and decryption. A few options here are algorithm, insecure_mode, and mode.
class User < ApplicationRecord
  attr_encrypted :secret, key: "user secret key"
  1. When accessing the new columns data, you can leave off the encrypted prefix to get the actual value, or keep the encrypted prefix to get the encrypted value.
# returns plain text

# returns encrypted
  1. When saving the new columns data you will save it with the encrypted prefix. There is also a method defined on the ActiveRecord model for encrypting the columns data, in this case User.encrypt_secret.
  encrypted_secret: User.encrypt_secret(SecureRandom.urlsafe_base64)