Data Encryption In Ruby On Rails

Tram Ho


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

Step 2: Install gem

At the console screen run the command

Step 3: Create a model

Step 4: Add the data you want to encrypt into the migration file

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:

field iv aims to make the data more secure

Step 5: Setting Model UserDetails

In the UserDetail.rb file we add:

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:

In the controllser, add permit params

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).

And you will see the data returned in unencrypted form.


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.


Share the news now

Source : Viblo