public function getAuthFor($sPath) { $sPath = $sPath[0] == '/' ? $sPath : '/' . $sPath; $iExpires = time() + 5 * 60; $sToSign = "GET\n\n\n{$iExpires}\n{$sPath}"; $oCrypt = new HMAC($this->sSecret, 'sha1'); $sSignature = $oCrypt->hash($sToSign); $sSignature = $this->base64($sSignature); $sAuth = '?'; $sAuth .= 'AWSAccessKeyId=' . $this->sKey . '&'; $sAuth .= 'Signature=' . urlencode($sSignature) . '&'; $sAuth .= 'Expires=' . $iExpires; return $sAuth; }
protected function sign($hParams) { $hParams['Version'] = $this->sVersion; $hParams['AWSAccessKeyId'] = $this->sKey; $hParams['Expires'] = date('c', time() + 120); $hParams['SignatureVersion'] = 1; // TODO redo this part $hSignedParams = $hParams; $aKeys = array_keys($hSignedParams); foreach ($aKeys as $i => $key) { $aKeys[$i] = strtolower($key); $hMap[strtolower($key)] = $key; } sort($aKeys); $sString = ''; foreach ($aKeys as $key) { $val = $hSignedParams[$hMap[$key]]; $sString .= $hMap[$key] . $val; } $oCrypt = new HMAC($this->sSecret, 'sha1'); $sSignature = $oCrypt->hash($sString); $sSignature = $this->hex2b64($sSignature); $hParams['Signature'] = $sSignature; return $hParams; }
echo sprintf("date : %s \n", date('Y-m-d H:i:s', $runtime)); $input = ['mobile' => 18612341234, 'partner' => $partner, 'user_id' => 1017, 'timestamp' => $runtime, 'channel' => $channel]; // 签名示范 $sign = HMAC::calculate($input, $key); echo sprintf("sign : %s\n", $sign); $queryData = array_merge($input, ['sign' => $sign]); $queryString = http_build_query($queryData); // 固定入口 URL 示范,其他接口类似 $fullUrl = $baseUrl . '/autoLogin?' . $queryString; echo sprintf("fullUrl : %s\n", $fullUrl); // 验签示范 if (HMAC::checkExpired($queryData['timestamp'])) { echo sprintf("链接已过期\n", $fullUrl); exit; } $result = HMAC::compare($queryData, $key, $sign); echo sprintf("compare result : %s\n", intval($result)); echo "DONE\n"; class HMAC { const TIME_SCOPE = 300; //second 5*60=300 /** * 计算签名 * @param $input * @param $key * @return string */ public static function calculate($input, $key) { $signPars = "";