Sha256: 28a677467688dfbd5a2dbf1882c0655684a6136ba421ca7e6b11f8c1e828cfc2

Contents?: true

Size: 1.22 KB

Versions: 11

Compression:

Stored size: 1.22 KB

Contents

# coding: utf-8
module RockFintech
  module Sign

    def self.sign(data, config)
      serialize_str = serialize(data)
      Sign::MD5.sign(serialize_str, Sign::MD5.sign(config[:rft_key], config[:rft_secret]))
    end # sign

    def self.verify(data, config)
      sign_str = data.delete(:sign)
      self.sign(data, config) == sign_str
    end # verify

    private

    def self.serialize(data_in)
      data = Marshal.load( Marshal.dump(data_in) ) # deep clone, not affect original data
      data = Hash[data.sort]     # key 按照 alphabet 排序

      data.each{ |k, v|
        if v.kind_of?(Hash)      # 如果是 hash 接着 serialize
          data[k] = serialize(v)
        elsif v.kind_of?(Array)
          if v[0].kind_of?(Hash) # 如果是 hash 数组对元素接着 serialize
            v.each_with_index{ |ele, index|
              ele.delete('sign')
              ele.delete(:sign)
              ele = Hash[ele.sort]
              v[index] = ele.map{|k,v| "#{k}=#{v}"}.join('&')
            }
            data[k] = v.join('&')
          else                   # 如果是普通元素数组
            data[k] = v.join('&')
          end
        end
      }
      data.map{|k,v| "#{k}=#{v}"}.join('&')
    end # serialize

  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
rock_fintech-0.19.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.18.4 lib/rock_fintech/sign/sign.rb
rock_fintech-0.18.1 lib/rock_fintech/sign/sign.rb
rock_fintech-0.17.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.16.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.15.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.14.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.13.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.12.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.11.0 lib/rock_fintech/sign/sign.rb
rock_fintech-0.10.0 lib/rock_fintech/sign/sign.rb