【发布时间】:2015-09-04 09:33:51
【问题描述】:
我正在尝试使用 rails 中的自定义列序列化程序加密一些 JSON 数据。因为加密需要是可逆的,所以我使用 AES 256 CBC 和密钥和初始化向量 (IV)。
我希望 key 和 iv 对于每条记录都是唯一的,这些记录具有提供这两个值的实例方法。我现在遇到的问题是我无法访问序列化器/编码器内部的记录实例,所以我不确定如何将这些值传递给它。
这是一些伪代码:
class MyModel
serialize :keys, EncryptedJSON
def data_encryption_key
Digest::SHA2.new(256).hexdigest("#{user.id}:#{user.created_at.utc.to_i}:#{ENV["SOME_SECRECT_KEY_VALUE"]}")
end
def data_encryption_iv
Digest::SHA2.new(256).hexdigest(user.created_at.utc.to_i)
end
end
class EncryptedJSON
require 'openssl'
# decode, decrypt and convert to json
def self.load(encrypted)
return if encrypted.nil?
decipher = OpenSSL::Cipher::AES.new(256, :CBC)
decipher.decrypt
# I want this to use: record.data_encryption_key()
decipher.key = Digest::SHA2.new(256).hexdigest("123")
# I want this to use: record.data_encryption_iv()
decipher.iv = Digest::SHA2.new(256).hexdigest("123")
encrypted = Base64.decode64(encrypted)
decrypted = decipher.update(encrypted) + decipher.final
JSON.parse(decrypted)
end
# convert to string, encrypt and encode
def self.dump(data)
return if data.nil?
cipher = OpenSSL::Cipher::AES.new(256, :CBC)
cipher.encrypt
# I want this to use: record.data_encryption_key()
cipher.key = Digest::SHA2.new(256).hexdigest("123")
# I want this to use: record.data_encryption_iv()
cipher.iv = Digest::SHA2.new(256).hexdigest("123")
encrypted = cipher.update(data.to_s) + cipher.final
Base64.encode64(encrypted)
end
end
【问题讨论】:
标签: ruby-on-rails security encryption