这个PHP函数应该如何在Ruby中查找? HMAC MD5

时间:2015-04-14 11:13:38

标签: php ruby hmac payu

我正在进行支付集成,并且我已经在PHP中获得了一个示例代码,并尝试使其在Ruby中运行。到目前为止收效甚微。如果我做错了什么,有人可以检查我的实施并修复吗?感谢。

PHP代码:

/*
* HMAC HASH creation
* RFC 2104
* 
http://www.ietf.org/rfc/rfc2104.txt
* 
* @param string $key Secret key for encryption
* @param string $data String to encode
*/
function hmac($key, $data) {
 $b = 64; // byte length for md5

 if (strlen($key) > $b) {
   $key = pack("H*", md5($key));
 }

 $key = str_pad($key, $b, chr(0x00));
 $ipad = str_pad('', $b, chr(0x36));
 $opad = str_pad('', $b, chr(0x5c));
 $k_ipad = $key ^ $ipad;
 $k_opad = $key ^ $opad;

 return md5($k_opad . pack("H*", md5($k_ipad . $data)));
}

我的Ruby代码:

    #Calculate HMAC MD5 PayU hash for order.
    def hmac_calculation(key, data)
      b = 64

      if key.length > b 
        key = Digest::MD5.hexdigest(key)
        key = key.pack("H*")
      end

      key = key.ljust(b, 0x00.chr)
      ipad = ''.ljust(b, 0x36.chr)
      opad = ''.ljust(b, 0x5c.chr)

      k_ipad = key ^ ipad
      k_opad = key ^ opad

      return Digest::MD5.hexdigest(k_opad + Digest::MD5.hexdigest(k_ipad + data).pack('H*'))    

    end

- 更新 -

来源字符串:

7P0499016123456192013-07-08 10:50:367sku000226Loremipsumdolorsitamet4112011102103HUF158CCVISAMC41010

密钥:

|!?n4A8〜3T8 ^ 3 [8%I 8 @ Q

预期结果:

5142968ed89754e8d3a9b9a2469d21f2

我也将此网站作为参考点,但上面的示例与之不符。 http://hash.online-convert.com/md5-generator

2 个答案:

答案 0 :(得分:5)

没有理由编写自己的HMAC实现,并且有许多原因没有。只需使用OpenSSL module提供的安全且经过良好测试的实现:

require "openssl"

key = "key"
data = "Hello"

digest = OpenSSL::Digest.new('md5')
hmac = OpenSSL::HMAC.hexdigest(digest, key, data)

这就是你所需要的一切。

答案 1 :(得分:0)

毕竟我再试一次,似乎PayU的原始要求是错误的。根本没有解决方案符合他们的预期结果。

    require 'openssl'

    key = '|n4A8~!3T8^3[8%I?8@Q'

    string = '7P0499016123456192013-07-08 10:50:367sku000226Loremipsumdolorsitamet4112011102103HUF158CCVISAMC41010'

    digest = OpenSSL::Digest.new('md5')

    hmac = OpenSSL::HMAC.hexdigest(digest, key, string)

    puts hmac # Result = 7e84e5a7ceff25a8400ecf9608aed731