Rails实现字段加密存储(rail是什么意思)干货满满

随心笔谈3年前发布 admin
216 0 0

文章摘要

这篇文章主要介绍了如何实现自定义的`EncryptedStringSerializer`类,该类用于对字符串进行加密和解密操作。该类通过`load`方法加载字符串并进行解密,通过`dump`方法加密字符串后进行存储或传输。此外,文章还展示了如何将这个加密机制应用到`UserAddress`活跃记录类中,通过配置`serialize`方法,将多个字段(如电话号码、姓名、地址等)进行加密处理。文章的核心内容在于通过自定义的加密解密功能,保护敏感数据的安全性。


class EncryptedStringSerializer
def self.load(value)
value.to_s.blank? ? ” : decrypt(value)
end

def self.dump(value)
encrypt(value || ”)
end

private

def self.encrypt(value)
encryptor.encrypt_and_sign(value)
end

def self.decrypt(value)
encryptor.decrypt_and_verify(value)
end

def self.encryptor
@encryptor ||=ActiveSupport::MessageEncryptor.new(Settings.message_encryptor_key)
end
end

class UserAddress < ActiveRecord::Base
serialize :phone, EncryptedStringSerializer
serialize :first_name, EncryptedStringSerializer
serialize :last_name, EncryptedStringSerializer
serialize :country, EncryptedStringSerializer
serialize :state, EncryptedStringSerializer
serialize :city, EncryptedStringSerializer
serialize :address1, EncryptedStringSerializer
serialize :address2, EncryptedStringSerializer
serialize :zipcode, EncryptedStringSerializer
end

© 版权声明

相关文章