0

Actually, I started with encrypting user_pass field with hard-coded key.

class Credential < ApplicationRecord
  ..
  attr_encrypted :user_pass, key: 'This is a key that is 256 bits!!'
  ..
end

I already have some data encrypted with this key. Now, I don't want to save the key in hard coded format, so saving the half key in file system and another half in table and combining them.

class Credential < ApplicationRecord
  ..
  attr_encrypted :user_pass, key: :encryption_key
  ..

  def encryption_key
    Rails.root.join('private', 'key').read + Setting.where(name: 'key').last.value
  end
end

How do I encrypt already encrypted data with current key?

Rajkaran Mishra
  • 4,532
  • 2
  • 36
  • 61
  • so obviously you will need to loop over the table data and in process of decrypting old key and then encrypt it with new key. That all you can do in db migration. Create new migration and inside make a loop to read and encrypt current data and after that line use you new crypt key. All that in migration, which you will at the end run as rails db:migrate and do all that... – Nezir Oct 02 '18 at 13:26

1 Answers1

1

What you can do is write another field, with the new key:

attr_encrypted :user_pass, key: 'This is a key that is 256 bits!!'
attr_encrypted :user_pass2, key: :encryption_key

Then you can migrate the data.

credential.user_pass2 = user.user_pass
credential.save

After this migration is done, you can either point your other code to the new field. Or drop/rename the old one and rename user_pass2 to user_pass (so that other code keeps working).

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367