Update encrypted fields for a different key

396 views Asked by At

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?

1

There are 1 answers

0
Sergio Tulentsev On BEST ANSWER

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