crypt_keeper icon indicating copy to clipboard operation
crypt_keeper copied to clipboard

`decrypt_table!` fails with unencrypted data

Open darkporpoise opened this issue 8 months ago • 0 comments

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

darkporpoise avatar Jun 04 '24 15:06 darkporpoise