Based on previous answer, a complete migration in both directions:
class SwitchToRailsBuiltInEncryption < ActiveRecord::Migration[7.0]
ATTRIBUTES = [
[Account, :password],
[Account, :client_secret],
]
def up
ATTRIBUTES.each do |klass, attribute|
klass.reset_column_information
add_column klass.table_name, attribute, :string, length: 510
klass.all.each do |record|
puts "Processing #{klass} with ID #{record.id}"
if record.send("encrypted_#{attribute}").present?
encrypted_value = record.send("encrypted_#{attribute}")
iv = record.send("encrypted_#{attribute}_iv")
value = decrypt(encrypted_value, iv)
record.update!(attribute => value)
end
end
remove_column klass.table_name, "encrypted_#{attribute}"
remove_column klass.table_name, "encrypted_#{attribute}_iv"
end
end
def down
ATTRIBUTES.each do |klass, attribute|
add_column klass.table_name, "encrypted_#{attribute}", :string, length: 510
add_column klass.table_name, "encrypted_#{attribute}_iv", :string, length: 510
klass.all.each do |record|
puts "Processing #{klass} with ID #{record.id}"
if record.send(attribute).present?
encrypted_value, iv = encrypt(record.send(attribute))
record.update!("encrypted_#{attribute}" => encrypted_value, "encrypted_#{attribute}_iv" => iv)
end
end
remove_column klass.table_name, attribute
end
end
# based on https://github.com/gorails-screencasts/migrate-attr_encrypted-to-rails-7-encryption/blob/master/db/migrate/20211005214633_migrate_encrypted_attributes.rb
# as suggested by https://stackoverflow.com/questions/72096672/using-attr-encrypted-with-rails-7
def decrypt(encrypted_value, iv)
value = Base64.decode64(encrypted_value)
cipher = OpenSSL::Cipher.new("aes-256-gcm")
cipher.decrypt
cipher.key = Rails.application.credentials.key
cipher.iv = Base64.decode64(iv)
cipher.auth_tag = value[-16..]
cipher.auth_data = ""
cipher.update(value[0..-17]) + cipher.final
end
def encrypt(value)
cipher = OpenSSL::Cipher.new("aes-256-gcm")
cipher.encrypt
cipher.key = Rails.application.credentials.key
iv = cipher.random_iv
cipher.auth_data = ""
encrypted_value = cipher.update(value) + cipher.final
return Base64.encode64(encrypted_value + cipher.auth_tag), Base64.encode64(iv)
end
end