'Rails 7 Active Record Encryption key on a record level
Hello all I would like to use Rails 7 attribute encryption on a model and have a unique key for each record. The main objective is that I would like to delete a key and never be able to decipher the encrypted information (on that record) again if requested.
I tested the code below and was able to encrypt the data in the DB, retrieve, and search, but the removal of the key is still allowing the retrieval of the information. Any help appreciated.
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
