Introduce
Data security is a very important issue in any application. Because we are storing user personal data such as date of birth, mobile phone number, address, bank information, etc.
Therefore, we should implement data security function with any user information. There are many gem
available in the Ruby On Rails library. But I will deploy gem attr_encrypted
.
Step 1: Add the attr_encrypted gem
In the GemFile directory add lines
1 2 | gem "attr_encrypted" |
Step 2: Install gem
At the console screen run the command
1 2 | bundle install |
Step 3: Create a model
1 2 | rails g model User |
Step 4: Add the data you want to encrypt into the migration file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 for example we want to encode the 2 information which is the date of birth and phone number. We add the encrypted
prefix before the column name. For example:
1 2 | t.string :encrypted_birth_date |
field iv
aims to make the data more secure
Step 5: Setting Model UserDetails
In the UserDetail.rb
file we add:
1 2 3 4 5 6 7 8 9 | 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 |
Step 6: Access encrypted information outside the view or on the rails console
To access encrypted information outside the view or on the rails console. You just need to name the school (without the encrypted
prefix). Example: Outside view:
1 2 3 | <%= f.text_field :birth_date, class: 'form-control' %> <%= f.text_field : mobile_no, class: 'form-control' %> |
In the controllser, add permit params
1 2 3 4 5 | private def user_details_params params.require(:user_detail).permit(:id, :last_name, :birth_date, :mobile_no) end |
In the rails console screen: 1. First we create a new record: In the above example, you can look at the log to see that the 2 birth_date and mobile_no information have been encrypted 2. Get the information of the newly created record: When you need to get information, you just need to call the name of the field (without the encryption
prefix).
1 2 3 4 | usr = UserDetail.find(1) usr.birth_date usr.mobile_no |
And you will see the data returned in unencrypted form.
Conclude:
With the need to secure information for data, the gem attr_encrypted
has met our basic needs. The above article has introduced people to the basic usage of gem attr_encrypted
. Hope the article is useful for everyone. Thanks for everyone who has read your article.
Source:
https://itnext.io/data-encryption-in-ruby-on-rails-4512fea27893