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.
- Install a third party gem, attr_encrypted
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 will be the key used to handle the actual encryption and decryption. A few options here are
class User < ApplicationRecord attr_encrypted :secret, key: "user 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) )