All posts

Rails db encryption cheatsheet

!Important. The lastest versions of Rails now ship with this functionality without needing the attr_encrypted gem.

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 brief reference for developers with some experience using 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 below will be the key used to handle the actual encryption and decryption. A few other keyword options to the attr_encrypted method are available are algorithm, insecure_mode, and mode.
class User < ApplicationRecord
  attr_encrypted :secret, key: "the 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)

More Ruby cheatsheets: Ruby HTTP gem, Rails params, Rails error handling


I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).