Data Encryption In Ruby On Rails


Data security is the main concern in any application.Because we are storing the user's personal data such as date of birth, mobile number, address, bank details and etc.

So you are at the right place to implement the data security functionality.
Here we are using the Ruby(4.2.5) and Postgresql(to store the user's data).

There are multiple gems available in Ruby On Rails.But we are going to implement the "attr_encrypted" Gem.

Step1. Add data encryption gem
add a gem in GemFile.

gem 'attr_encrypted'

Step2. Perform the bundle install

bundle install

Step3. Generate a model

rails g model UserDetail

Step4. Set encrypted columns in migration file.

class CreateUserDetails < ActiveRecord::Migration
  def change
    create_table :user_details do |t|
      t.string :last_name
      t.string :first_name
      t.string :encrypted_birth_date
      t.string :encrypted_birth_date_iv
      t.string :encrypted_mobile_no
      t.string :encrypted_mobile_no_iv
      t.timestamps null: false
    end
  end
end

In the migration file, we need to encrypt birth_date and mobile_no.
So, we have to add 「encrypted_」string before column name.
For example, birth_date.
so,our migration file look like,

t.string :encrypted_birth_date
t.string :encrypted_birth_date_iv

iv column is used for more data security.

Step5. Setting in Model
in your model,

class UserDetail < ActiveRecord::Base
    secret_key = ENV['DB_COL_ENCRYPTED_KEY']
    attr_encrypted :birth_date, :key => secret_key
    attr_encrypted :mobile_no, :key => secret_key
    validates_presence_of :last_name
    validates_presence_of :first_name
    validates_presence_of :birth_date 
end

for environment variables setting, please check the below article.
http://qiita.com/alokrawat050/items/0d7791b3915579f95791

Step6. How to access encrypted fields in view or rails console
If you need to access encrypted fields in views or rails console then you just need to write the column name(no need to write the encrypted_).

in views,

<%= f.text_field :birth_date, class: 'form-control'  %>
<%= f.text_field : mobile_no, class: 'form-control'  %>

in your controller, set the permit params,

private
    def user_details_params
      params.require(:user_detail).permit(:id, :last_name, :birth_date, :mobile_no)
    end

in rails console,
rails c

1.data insert in user_details table.

In above example, you can see that when we are going to save data then it encrypted both the column's data(birth_date and mobile_no).

2.data fetch from user_details table.

when we are fetching data then we need to call only column name(no need to write the encrypted_).

usr = UserDetail.find(1)
usr.birth_date
usr.mobile_no

and you will get the data in decrypted form.

Enjoy Coding.

Thanks & Best Regards,
Alok Rawat