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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器