ruby 使用ssl加密的活动记录
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 使用ssl加密的活动记录相关的知识,希望对你有一定的参考价值。
require 'openssl'
require 'digest/sha1'
require 'base64'
require 'json'
class Setting < ActiveRecord::Base
belongs_to :user, inverse_of: :settings
serialize :content, JSON
validates :user, presence: true
validates :name, presence: true, format: /\A[a-z0-9_\.]+\z/
@decrypted = nil
before_save do
@decrypted = content
self.content = encrypt(content)
end
after_save do
self.content = @decrypted
end
after_find do
self.content = decrypt(content)
end
private
def encrypt(content)
content = ActiveSupport::JSON.encode(content)
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt
random_iv = cipher.random_iv
self.salt = Base64.encode64(random_iv)
cipher.key = crypt_key
cipher.iv = random_iv
encrypted = cipher.update(content)
encrypted << cipher.final
Base64.encode64(encrypted)
end
def decrypt(content)
content = Base64.decode64(content)
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.decrypt
cipher.key = crypt_key
cipher.iv = Base64.decode64(salt)
decrypted = cipher.update(content)
decrypted << cipher.final
ActiveSupport::JSON.decode(decrypted)
end
def crypt_key
Digest::SHA1.hexdigest(ENV['APP_SETTINGS_SALT'])
end
end
以上是关于ruby 使用ssl加密的活动记录的主要内容,如果未能解决你的问题,请参考以下文章
什么是SSL加密,什么是TLS加密
安信SSL证书新春特惠活动继续 全场7折起
Ruby活动记录在mysql中插入日期时间而不是时间
ruby 活动记录有用的命令
简单记录下HTTPS中的SSL
如何使普通的 ruby 对象可分配为活动记录关联