crypt_keeper
crypt_keeper copied to clipboard
`decrypt_table!` fails with unencrypted data
This might just be one to document as it might save someone in the future a couple of hours:
If you have an encrypted field, but not every row in the database has been encrypted, then Model.decrypt_table!
will fail with ActiveSupport::MessageEncryptor::InvalidMessage
.
I think this must have come about in my data because a new field with existing data has been added to the list.
I got round it by just adding a decrypt_table!
class method to the model in question which suppresses the error:
# models/application_record
def self.decrypt_table!
tmp_table = Class.new(ActiveRecord::Base).tap {|c| c.table_name = self.table_name}
transaction do
tmp_table.find_each do |r|
crypt_keeper_fields.each do |field|
begin
r.send("#{field}=", encryptor.decrypt(r[field])) if r[field].present?
rescue ActiveSupport::MessageEncryptor::InvalidMessage
end
end
r.save!
end
end
end