douzhaochan6468 2013-03-25 01:08
浏览 108
已采纳

无法使用PHP base64_encode获取Twitter的OAuth签名

I'm working through Twitter's Creating a Signature Doc.

I've taken the example signature base string, and the example signing key, and passed it to the hash_hmac function, as recommended in the doc:

$sig_base_str = 'POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521';
$sig_key = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE';
$sha = hash_hmac('sha1', $sig_base_str, $sig_key);
$sha = strtoupper($sha);
$output = str_split($sha,2);
$output = implode(' ',$output);
echo $output;

This gives me the exact same binary as in the example: B6 79 C0 AF 18 F4 E9 C5 87 AB 8E 20 0A CD 4E 48 A9 3F 8C B6.

Now, the doc says to convert it to base64. I believe that I can use PHP's base64_encode() function:

$sha = hash_hmac('sha1', $sig_base_str, $sig_key);
echo base64_encode($sha);

But this gives me an incorrect value for my OAuth_signature:

YjY3OWMwYWYxOGY0ZTljNTg3YWI4ZTIwMGFjZDRlNDhhOTNmOGNiNg==

View http://ideone.com/Bu0CZi to see the function in action.

What am I doing wrong? Note, that I've also tried to convert to uppercase and include spaces before the base64_encode() function. I've been having troubles using Twitter API, and I think it's because I can't get the signature correct, even in the examples in the docs.

  • 写回答

1条回答 默认 最新

  • douhuang3833 2013-03-25 02:47
    关注

    I was getting the correct hashed value in hexidecimal characters, but I needed them in raw binary data:

    $sha = hash_hmac('sha1', $sig_base_str, $sig_key, true);
    echo base64_encode($sha);
    

    Outputs: tnnArxj06cWHq44gCs1OSKk/jLY= Exactly as it should in the Twitter docs.

    Got my answer from looking up the twitteroauth library: https://github.com/abraham/twitteroauth/blob/master/twitteroauth/OAuth.php#L116

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog