HMAC-SHA1 常用於 API 簽名驗證(如 OAuth 1.0、AWS 簽名)、資料完整性校驗。本函式支援 PHP 內建 hash_hmac(高效能)與純 PHP 手動實作(舊版本相容)雙模式自動切換。
<?php
/**
* 使用 HMAC-SHA1 算法生成簽名值
*
* @param string $str 待簽名的原始字串
* @param string $key 密鑰
* @return string Base64 編碼的簽名值
*/
function getSignature($str, $key) {
$signature = "";
// 優先使用內建函式(PHP 5.1.2+)
if (function_exists('hash_hmac')) {
// true 表示輸出原始二進位資料,再 Base64 編碼
$signature = base64_encode(hash_hmac("sha1", $str, $key, true));
} else {
// 純 PHP 實作 HMAC-SHA1(RFC 2104)
$blocksize = 64;
$hashfunc = 'sha1';
// 密鑰長度超過區塊大小,先雜湊縮短
if (strlen($key) > $blocksize) {
$key = pack('H*', $hashfunc($key));
}
// 密鑰補零至區塊大小
$key = str_pad($key, $blocksize, chr(0x00));
// inner/outer padding
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
// HMAC = H(K ⊕ opad || H(K ⊕ ipad || text))
$hmac = pack(
'H*',
$hashfunc(
($key ^ $opad) . pack(
'H*',
$hashfunc(($key ^ $ipad) . $str)
)
)
);
$signature = base64_encode($hmac);
}
return $signature;
}
?>
<?php
$secret_key = 'my_secret_key';
$message = 'GET&/api/resource¶m1=value1';
$signature = getSignature($message, $secret_key);
echo "Signature: $signature\n";
// 輸出類似:k7vX9pQ2mR8nL3zY6wT5uI1oP0s=
?>
+///=)。$hashfunc = 'sha256' 且 $blocksize = 64(SHA256 區塊同為 64 位元組)。hash_equals()(PHP 5.6+)而非 == 比較。生產環境請確保 PHP 版本 ≥ 5.1.2 以使用內建 hash_hmac,效能較手動實作高數十倍。若必須在舊版本運行,建議安裝 pecl/hash 擴展。