attr_encrypted is a nice gem for encrypting fields in Rails.
You add this line to a model: attr_encrypted :field_name, key: ENV['attr_encrypted_key']
. I used rake secret
to generate that attr_encrypted_key
referenced in that line.
The field itself needs to be created in a particular way in the migration:
add_column :table_name, :encrypted_field_name, :text
add_column :table_name, :encrypted_field_name_iv, :text
So, you're taking whatever field_name
you want (e.g. ssn
), and creating the fields in the database as encrypted_ssn
and encrypted_ssn_iv
.
In forms, you use the non-encrypted field name (this means the value is shown to the user on the page):
<%= simple_form_for(record_name) do |f| %>
<%= f.input :ssn, as: :string %>
<%= f.button :submit %>
<% end %>
As far as using the fields go, you use the encrypted_field_name
version if you want to display the encrypted version & field_name
version if you want to display the unencrypted version.
You can also redact this information from the Rails logs by editing the config/initializers/filter_parameter_logging.rb
file to include the field(s):
Rails.application.config.filter_parameters += [:encrypted_ssn, :ssn, :password]
I chose to encrypt both, just in case. I didn't verify which value is logged.