Rails 7主动记录加密密钥在记录级别
您好,我想在模型上使用Rails 7属性加密,并为每个记录具有唯一的键。主要目的是我想删除一个密钥,并且如果要求(在此要求)再次(在该记录上)破译了加密信息。
我测试了下面的代码,并能够在数据库中加密数据,检索和搜索,但是删除密钥仍允许检索信息。任何帮助都赞赏。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论