2

I am using attr_encrypted, and have some data encrypted with a key that I no longer have access to. I would like to overwrite the existing/old data with new data, using a new key. How can I do this?

For example, consider this:

class User
    attr_encrypted :account_number,  key: ENV['ATTR_ENCRYPTED_KEY'] # new key
end

The following attempt fails with OpenSSL::Cipher::CipherError

u = User.first
u.account_number = '123456789' # error here!
u.save 

Based on the stack trace (below), I believe it is due to the fact that attr_encrypted tries to decrypt first - which clearly won't work due to the fact that the key is different. Is there a way to circumvent that, and just write the new data and iv, with a new key?

.../gems/encryptor-3.0.0/lib/encryptor.rb:98:in `final'
.../gems/encryptor-3.0.0/lib/encryptor.rb:98:in `crypt'
.../gems/encryptor-3.0.0/lib/encryptor.rb:49:in `decrypt'
.../bundler/gems/attr_encrypted-399c5dd168ca/lib/attr_encrypted.rb:246:in `decrypt'
.../bundler/gems/attr_encrypted-399c5dd168ca/lib/attr_encrypted.rb:335:in `decrypt'
.../bundler/gems/attr_encrypted-399c5dd168ca/lib/attr_encrypted.rb:164:in `block (2 levels) in attr_encrypted'
.../bundler/gems/attr_encrypted-399c5dd168ca/lib/attr_encrypted/adapters/active_record.rb:76:in `block in attr_encrypted'
user664833
  • 18,397
  • 19
  • 91
  • 140
  • 1
    Have you tried deleting the attribute via the database instead of ActiveRecord? There are two columns `encrypted_#{attr}` and `encrypted_#{attr}_iv`. If you don't care about the old data I think clearing those would allow you to write to them again via AR. – Tom Dec 12 '18 at 22:58
  • 1
    Yes, why don't you just make `User.update_all account_number: nil` on both attributes and then just create a rake task to update them again, if they are nil I think there will not be problems to update them. – xploshioOn Dec 12 '18 at 23:02
  • 1
    Thanks a lot! These are great comments, and they helped me figure this out. My model actually has more than one encrypted field (not just `account_number`, but others too - I just didn't mention them so as to keep things brief). I had already tried clearing the `account_number` and only overwriting it; but it wasn't until I cleared all encrypted fields (with `update_all`) that I was able to overwrite the old data and save it (perhaps due to validation errors that I wasn't seeing for some reason - presently not sure... I will look into this some more.) – user664833 Dec 12 '18 at 23:32

0 Answers0