!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.
Install a third party gem,
gem install attr_encrypted
- 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
Add the method
attr_encryptedto 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_encryptedmethod are available are
class User < ApplicationRecord attr_encrypted :secret, key: "the secret key" end
- 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 User.last.secret # returns encrypted User.last.encrypted_secret
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.create( encrypted_secret: User.encrypt_secret(SecureRandom.urlsafe_base64) )