Hello all I would like to use Rails 7 attribute encryption on a model and have a unique key for each record/instance. The main objective is that I would like to be able to delete a key associated with a record (instance) and never be able to decipher the encrypted information (on that record) again if requested. I am testing this for GDPR compliance and think it would be a nice way to forget personal information and not worry about backups and such.
I have tested a few ways and am not able to accomplish this. All help appreciated.
Latest try
class User < ActiveRecord::Base
after_initialize :user_encryption_key
after_save :create_key_record
attr_accessor :p_encryption_key
def self.instance_encryption_key
if self.respond_to?(:p_encryption_key)
puts "This is the key - #{self&.p_encryption_key}"
self&.p_encryption_key
else
nil
end
end
encrypts :last_name,
deterministic: true,
key: self.instance_encryption_key
def user_encryption_key
if user_id
self.p_encryption_key = get_user_encryption_key
else
# new record without an ID let the after save create the DB
# entry
self.p_encryption_key = create_encryption_key
end
end
def profile_key_name
%{/user_key/#{user_id}}
end
def get_user_encryption_key
Rails.cache.
fetch(user_key_name) {create_encryption_key}
end
def create_encryption_key
ActiveRecord::Encryption::KeyGenerator.new.
generate_random_hex_key(length: 16)
end
def create_key_record
if new_record?
if p_encryption_key.nil?
p_encryption_key = create_encryption_key
end
Rails.cache.
fetch(profile_key_name) {create_encryption_key}
end
end
end