核心函數:getSignature()
/**
* 使用 HMAC-SHA1 產生 OAuth 簽名
* @param string $baseString 簽名基礎字串 (已編碼)
* @param string $key 簽名金鑰 (consumer_secret + "&" + token_secret)
* @return string Base64 編碼的簽名
*/
function getSignature(string $baseString, string $key): string {
// PHP 5.1.2+ 內建 hash_hmac (需 hash 擴充,預設開啟)
if (function_exists('hash_hmac')) {
// raw_output=true 取得原始二進制,再 base64_encode
return base64_encode(hash_hmac('sha1', $baseString, $key, true));
}
// 相容舊版純 PHP 實作 (RFC 2104)
$blocksize = 64; // SHA-1 區塊大小
$hashfunc = 'sha1';
// 金鑰長度超過區塊大小先哈希
if (strlen($key) > $blocksize) {
$key = pack('H*', $hashfunc($key));
}
// 金鑰補零至區塊大小
$key = str_pad($key, $blocksize, chr(0x00));
// 內外部填充
$ipad = str_repeat(chr(0x36), $blocksize); // 0x36 = '6'
$opad = str_repeat(chr(0x5c), $blocksize); // 0x5c = '\'
// HMAC = H((K ⊕ opad) || H((K ⊕ ipad) || data))
$inner = pack('H*', $hashfunc(($key ^ $ipad) . $baseString));
$hmac = pack('H*', $hashfunc(($key ^ $opad) . $inner));
return base64_encode($hmac);
}
OAuth 1.0 簽名基礎字串構建
function buildBaseString(string $method, string $url, array $params): string {
// 1. 參數正規化:按鍵名 ASCII 排序,鍵值各自 RFC3986 編碼
ksort($params);
$pairs = [];
foreach ($params as $k => $v) {
$pairs[] = rawurlencode($k) . '=' . rawurlencode($v);
}
$paramStr = implode('&', $pairs);
// 2. URL 正規化:scheme://host/path (小寫、預設埠移除)
$parsed = parse_url($url);
$normUrl = strtolower($parsed['scheme']) . '://' . strtolower($parsed['host']);
$port = $parsed['port'] ?? ($parsed['scheme'] === 'https' ? 443 : 80);
if (($parsed['scheme'] === 'http' && $port != 80) || ($parsed['scheme'] === 'https' && $port != 443)) {
$normUrl .= ':' . $port;
}
$normUrl .= $parsed['path'] ?? '/';
// 3. 組合:METHOD + "&" + encoded(URL) + "&" + encoded(params)
return strtoupper($method) . '&' . rawurlencode($normUrl) . '&' . rawurlencode($paramStr);
}
完整 OAuth 1.0 簽名流程範例
$consumerKey = 'your_consumer_key';
$consumerSecret = 'your_consumer_secret';
$token = 'access_token';
$tokenSecret = 'access_token_secret';
$params = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(microtime() . mt_rand()),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $token,
'oauth_version' => '1.0',
// 業務參數...
'status' => 'Hello OAuth!',
];
$baseString = buildBaseString('POST', 'https://api.twitter.com/1.1/statuses/update.json', $params);
$signingKey = rawurlencode($consumerSecret) . '&' . rawurlencode($tokenSecret);
$signature = getSignature($baseString, $signingKey);
$params['oauth_signature'] = $signature;
// 發送請求 (Authorization Header)
$authHeader = 'OAuth ' . implode(', ', array_map(function($k, $v) {
return rawurlencode($k) . '="' . rawurlencode($v) . '"';
}, array_keys($params), $params));
$ch = curl_init('https://api.twitter.com/1.1/statuses/update.json');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => ['status' => 'Hello OAuth!'],
CURLOPT_HTTPHEADER => ['Authorization: ' . $authHeader],
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
關鍵細節提醒
- 編碼標準:OAuth 要求 RFC 3986 (rawurlencode),非 PHP 預設 urlencode (空格編為 +)
- 參數排序:按鍵名 ASCII 碼升序
- 金鑰組合:
consumer_secret & token_secret 中間以 & 連接,雙方各自 rawurlencode
- Base String:三部分均需 rawurlencode 後再以 & 連接
- Nonce:唯一隨機字串,防重放攻擊
- Timestamp:Unix 時間戳,伺服器通常允許 ±5 分鐘誤差
現代替代:hash_hmac() 單行解決
// PHP 5.1.2+ 直接使用
$signature = base64_encode(hash_hmac('sha1', $baseString, $key, true));
// 支援 sha256, sha512 等更強算法
$signature256 = base64_encode(hash_hmac('sha256', $baseString, $key, true));