gemfile 加如下代码
gem "ruby-mcrypt"
使用
require 'mcrypt' module Crypt def self.append_features(base) super base.extend(AesBase64) end module AesBase64 # require 'openssl' # require 'base64' # require 'hex_string' KEY = 'xyz' #you key IV = "123" # you iv def encrypt(data) crypto = Mcrypt.new(:rijndael_128, :cbc, KEY, IV, :zeros) enc = crypto.encrypt(escape(data)) # use for latter # aes = OpenSSL::Cipher::AES128.new('CBC') # aes.padding = 0 # aes.encrypt # aes.key = KEY # aes.iv = IV # enc = aes.update(data) << aes.final Base64.strict_encode64(enc) end def decrypt(data) base64 = Base64.strict_decode64(data) crypto = Mcrypt.new(:rijndael_128, :cbc, KEY, IV, :zeros) crypto.decrypt(base64) # use for latter # dec = Base64.strict_decode64(data) # aes = OpenSSL::Cipher::AES128.new('CBC').decrypt # aes.padding = 0 # aes.key = KEY # aes.iv = IV # aes.update(dec) << aes.final end def escape(string) if string.respond_to?(:force_encoding) string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY) end json = string. # gsub(escape_regex) { |s| ESCAPED_CHARS[s] }. gsub(/([\xC0-\xDF][\x80-\xBF]| [\xE0-\xEF][\x80-\xBF]{2}| [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s| s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&') } json = %(#{json}) json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding) json end end end