How to encrypt new data with new key using attr_encrypted (over old data)?

818 Views Asked by At

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'
0

There are 0 best solutions below