Rails和PHP编码64不同意

时间:2013-04-25 09:52:19

标签: php ruby-on-rails sha1 hmac

我尝试在Rails中创建HMAC并在PHP中验证它 Rails shell:

       pry(main)>appsecret = '00916893840fe0a29dfdc261efd3a26a&'           
       pry(main)>OpenSSL::HMAC.hexdigest('sha1', appsecret, 'GET&http%3A%2F%2Fopen.tianya.cn%2Foauth%2Frequest_token.php&oauth_consumer_key%3Dfc69b18eb12bab1e9b35d1093c4de9290516cfdc4%26oauth_nonce%3Dc09e4bf167fbc7eb374b1abb02b5268d%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1366882036%26oauth_version%3D1.0')
       => "8494f6237ee6042a3da8848db21284be17bf6ade"

PHP:

      $appsecret = '00916893840fe0a29dfdc261efd3a26a&';
      $signature = base64_encode(hash_hmac('sha1', $appsecret, 'GET&http%3A%2F%2Fopen.tianya.cn%2Foauth%2Frequest_token.php&oauth_consumer_key%3Dfc69b18eb12bab1e9b35d1093c4de9290516cfdc4%26oauth_nonce%3Dc09e4bf167fbc7eb374b1abb02b5268d%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1366882036%26oauth_version%3D1.0',true));
      var_dump($signature);

Rails结果:8494f6237ee6042a3da8848db21284be17bf6ade

PHP结果:ayw4 / L22fCtXPvPPGaY / Ud8yhMU =
任何帮助将非常感谢!

2 个答案:

答案 0 :(得分:1)

你有两个问题:

  1. 您的ruby输出以ascii hex形式返回,而不是raw,并且您不是base64编码它
  2. 您的PHP hash_hmac()函数的参数顺序错误。
  3. 红宝石:

    appsecret = '00916893840fe0a29dfdc261efd3a26a&'
    data = 'GET&http%3A%2F%2Fopen.tianya.cn%2Foauth%2Frequest_token.php&oauth_consumer_key%3Dfc69b18eb12bab1e9b35d1093c4de9290516cfdc4%26oauth_nonce%3Dc09e4bf167fbc7eb374b1abb02b5268d%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1366882036%26oauth_version%3D1.0'
    
    digest = OpenSSL::HMAC.digest('sha1', appsecret, data)
    Base64.encode64(digest)
    

    PHP:

    $appsecret = '00916893840fe0a29dfdc261efd3a26a&';
    $data = 'GET&http%3A%2F%2Fopen.tianya.cn%2Foauth%2Frequest_token.php&oauth_consumer_key%3Dfc69b18eb12bab1e9b35d1093c4de9290516cfdc4%26oauth_nonce%3Dc09e4bf167fbc7eb374b1abb02b5268d%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1366882036%26oauth_version%3D1.0';
    
    $digest = hash_hmac('sha1', $data, $appsecret, true);
    echo base64_encode($digest);
    

    两者都产生hJT2I37mBCo9qISNshKEvhe/at4=。但请注意,ruby输出也有一个尾随的换行符,因此如果要直接比较它们,则需要将其标准化(在ruby中删除它或在PHP中添加一个)。

答案 1 :(得分:0)

在尝试了不同的试验和错误后,我发现两种功能都是相似的......这样可以得到与红宝石相同的结果:

$appsecret = '00916893840fe0a29dfdc261efd3a26a&';
$signature = hash_hmac('sha1', 'GET&http%3A%2F%2Fopen.tianya.cn%2Foauth%2Frequest_token.php&oauth_consumer_key%3Dfc69b18eb12bab1e9b35d1093c4de9290516cfdc4%26oauth_nonce%3Dc09e4bf167fbc7eb374b1abb02b5268d%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1366882036%26oauth_version%3D1.0',$appsecret);
var_dump($signature);

结果:

string(40) "8494f6237ee6042a3da8848db21284be17bf6ade" 

在PHP中,hash_hmac的参数顺序在php中反转,首先是数据,然后是键。 ruby输出不是base64编码的,因此您不必在PHP中使用base64编码。