Skip to content

Instantly share code, notes, and snippets.

@JamesChevalier
Created July 28, 2016 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesChevalier/0d6873067f3d049c6200b0438737eaaa to your computer and use it in GitHub Desktop.
Save JamesChevalier/0d6873067f3d049c6200b0438737eaaa to your computer and use it in GitHub Desktop.
Quick description of attr_encrypted

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment