Rails和PHP不一致
我正在尝试在Rails中创建HMAC,并在PHP中验证它。Rails和PHP不一致,php,ruby-on-rails,sha1,hmac,Php,Ruby On Rails,Sha1,Hmac,我正在尝试在Rails中创建HMAC,并在PHP中验证它。 轨道外壳: pry(main)>appsecret = '00916893840fe0a29dfdc261efd3a26a&' pry(main)>OpenSSL::HMAC.hexdigest('sha1', appsecret, 'GET&http%3A%2F%2Fopen.tianya.cn%2Foauth%2Frequest_token.php&
轨道外壳:
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:
轨道结果:8494f6237ee6042a3da8848db21284be17bf6ade
PHP结果:ayw4/L22fCtXPvPPGaY/Ud8yhMU=
任何帮助都将不胜感激 您有两个问题:
两者都生产hJT2I37mBCo9qISNshKEvhe/at4=。但是,请注意,ruby输出也有一个尾随的新行,因此如果您想直接比较它们,则需要对其进行规范化(在ruby中删除它或在PHP中添加一行)。在尝试不同的尝试和错误后,我发现这两个功能是如何相似的。这将为您提供与ruby相同的结果:
$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编码。在ruby On rails上=>
00916893840FE0A29DFDC261EFD3A226A&=8494f6237ee6042a3da8848db21284be17bf6ade
在PHP=>上00916893840FE0A29DFDC261EFD3A226A&=ayw4/L22FCTXVPPGAY/UD8YHMMU=
?我认为散列hmac的参数顺序是在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);
$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"