如何在Ruby中实现敏感信息加密上传与解密使用方案?
Ruby中敏感信息加密解密实现方案
核心实现思路
- 选对称加密算法:因为需要解密敏感信息对接第三方应用,对称加密(如AES-256-GCM)效率高且适配场景,同时GCM模式自带完整性校验,能防止密文被篡改。
- 密钥安全管理:绝对不能把解密密钥硬编码到代码里,开发环境用环境变量,生产环境用专门的密钥管理服务,避免密钥泄露。
- 加密流程:先把敏感哈希序列化为字符串(比如JSON),再生成随机初始化向量(IV),用密钥+IV加密数据,最后把密文、IV、auth_tag(GCM模式必填)一起存储,解密时需要这些参数。
- 解密流程:从存储中读取密文和配套参数,用密钥反向解密,再反序列化为原哈希结构。
代码示例(基于Ruby内置OpenSSL)
用AES-256-GCM实现,无需额外依赖:
require 'openssl' require 'json' class SensitiveDataEncryptor ALGORITHM = 'aes-256-gcm' def initialize(key) # 确保密钥长度符合AES-256要求(32字节) @key = OpenSSL::Digest::SHA256.digest(key) end # 加密敏感哈希 def encrypt(data_hash) cipher = OpenSSL::Cipher.new(ALGORITHM) cipher.encrypt iv = cipher.random_iv cipher.key = @key # 序列化哈希为JSON字符串 plaintext = data_hash.to_json ciphertext = cipher.update(plaintext) + cipher.final # GCM模式需要保存auth_tag用于完整性校验 { ciphertext: Base64.strict_encode64(ciphertext), iv: Base64.strict_encode64(iv), auth_tag: Base64.strict_encode64(cipher.auth_tag) } end # 解密还原哈希 def decrypt(encrypted_data) cipher = OpenSSL::Cipher.new(ALGORITHM) cipher.decrypt cipher.key = @key cipher.iv = Base64.strict_decode64(encrypted_data[:iv]) cipher.auth_tag = Base64.strict_decode64(encrypted_data[:auth_tag]) ciphertext = Base64.strict_decode64(encrypted_data[:ciphertext]) plaintext = cipher.update(ciphertext) + cipher.final JSON.parse(plaintext, symbolize_names: true) end end # 使用示例 # 注意:密钥从环境变量读取,不要硬编码 encryption_key = ENV['ENCRYPTION_MASTER_KEY'] encryptor = SensitiveDataEncryptor.new(encryption_key) # 加密敏感数据 sensitive_data = { token: "blabla", email: "blabal@blabal.com" } encrypted = encryptor.encrypt(sensitive_data) # 把encrypted存储到数据库/服务器 # 解密数据 decrypted_data = encryptor.decrypt(encrypted) puts decrypted_data # => {:token=>"blabla", :email=>"blabal@blabal.com"}
可用工具建议
- Ruby内置OpenSSL:无需额外gem,安全性高,适合自定义加密逻辑,示例就是基于它实现的。
- attr_encrypted:针对Rails ActiveRecord模型的字段加密,只需给模型属性加
attr_encrypted声明,就能自动处理加密解密,适合快速开发Rails应用。 - lockbox:现代加密库,支持ActiveRecord、ActiveStorage等多种存储方式,配置简单,默认使用安全的加密算法,还支持密钥轮换。
- 密钥管理工具:开发环境用
dotenv管理环境变量;生产环境建议用专门的密钥管理服务,避免密钥暴露在代码或配置文件中。
内容的提问来源于stack exchange,提问作者user_pruser
相关产品推荐
相关产品推荐

