Djodjo
Djodjo

Reputation: 95

Encrypt existing fields of a model with attr_encrypted Rails

I want to install the following gem https://github.com/attr-encrypted/attr_encrypted to encrypt some fields of the existing models I have. For example, a User model with first_name, last_name, etc. My app is already deployed, so I don't want to make any stupid mistakes.

I understood how to process is with a new model through this link (https://qiita.com/alokrawat050/items/ff6dceec32baa0c8fa57), but how should I process with an existing db et models?

I was thinking about doing the following steps:

  1. Install the gem.
  2. Adding the following lines in my model:

    class User < ActiveRecord::Base
      secret_key = ENV['DB_COL_ENCRYPTED_KEY']
      attr_encrypted :first_name, :key => secret_key
      attr_encrypted :last_name, :key => secret_key
      [...]
    end
    
  3. Create a new migration:

    rails g migration AddEncryptedColumnsToUser encrypted_first_name:string encrypted_last_name:string encrypted_first_name_iv:string encrypted_last_name_iv:string 
    
  4. rake db:migrate


(Edited)

Following the above steps, when I look at the db in the console, I still have the first_name and last_name fields:

<User id: 2, first_name: "John", last_name: "Doe", 
encrypted_first_name: nil, encrypted_last_name: nil, 
encrypted_first_name_iv: nil, encrypted_last_name_iv: nil>

If I do:

User.update first_name: "John", last_name: "Doe"

It encrypts it correctly.

Next step is to remove the columns with first_name and last_name:

rails generate migration RemoveNonEncryptedDateFromUser first_name:string last_name:string

Is there a way to copy the non-encrypted fields first_name and last_name from the model and encrypt them directly, or do I have to do it manually for all of them?

Upvotes: 2

Views: 1215

Answers (0)

Related Questions