簡體   English   中英

計算HMAC-SHA1簽名

[英]Calculate HMAC-SHA1 Signature

我在PHP中獲得了下面的代碼,但是從未經授權的服務器中收到了一個錯誤,因此在計算oauth_signature字段的$ signature時可能會出錯。

未設置任何HTTP標頭。

        include_once "oauth-php/library/OAuthStore.php";
        include_once "oauth-php/library/OAuthRequester.php";

        $key = 'xx'; // this is your consumer key
        $secret = 'xx'; // this is your secret key
        $req_url = "http://www.sample.com"; 

        $options = array( 'consumer_key' => $key, 'consumer_secret' => $secret);

    OAuthStore::instance("2Leg", $options );

    $method = "POST";  

$ params = array('oauth_consumer_key'=> $ key,'oauth_signature_method'=>'HMAC-SHA1','oauth_timestamp'=> time(),'oauth_nonce'=> time(),'user_id'=>'1234' );

    $post_string = ''; 
foreach($params as $key => $value) {
        $post_string .= $key.'='.($value).'&'; 
} 
$post_string = rtrim($post_string, '&'); 
$base_string = urlencodeRFC3986($post_string); 
$signature = base64_encode(hash_hmac('sha1', $base_string, $secret, true));

$params['oauth_signature'] = $signature;
try {
            $request = new OAuthRequester($req_url, $method, $params);

            $result = $request->doRequest();
            var_dump($result); 
} 
catch(OAuthException2 $e)
{   
var_dump($e); 
}

function urlencodeRFC3986($string) 
{    
return str_replace('%7E', '~', rawurlencode($string)); 
}

一些東西:

1)不要將'oauth_signature_method'設置為array('HMAC-SHA1') 只需使用'HMAC-SHA1' ,否則您將在帖子字符串中使用oauth_signature_method=Array結束。

2)在計算完簽名后,請勿在參數列表中包含oauth_signature 有關更多詳細信息,請參閱此問題: https : //stackoverflow.com/questions/9986533/what-does-oauth-signature-sign

您應該以如下形式結束:

$params = array(
                'oauth_consumer_key' => $key, 
                'oauth_signature_method' =>  'HMAC-SHA1',
                'oauth_timestamp' => time(),
                'oauth_nonce' => time(),
                'user_id' => '1234'
                );

$post_string = '';
foreach($content as $key => $value)
{
    $post_string .= $key.'='.($value).'&';
}
$post_string = rtrim($post_string, '&');

$base_string = urlencodeRFC3986($post_string);

$signature = base64_encode(hash_hmac('sha1', $base_string, $secret, true));

$params['oauth_signature'] = $signature;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM