前言
secret_id: 密钥的Id
secret_key: 密钥的Key
SHA1: 签名方式
hash_hmac: php hash函数
hash_hmac_file:生成密钥
1.生成secret_key
hash_hmac_file('SHA1','signature.txt','secret');
2.生成签名
base64_encode(hash_hmac('SHA1', $init, $secret_key, true).$init);
3.签名比对
base64_decode($initSign);
base64_encode(hash_hmac('SHA1', $init, $secret_key, true).$init);
4.网站验证(sha1.html)
访问 sha1.html
5.代码
5.1 HashHmacSha1.php
class HashHmacSha1
{
/** code
* @var int
*/
protected $code = 200;
/** message
* @var string
*/
protected $message = 'success';
/** 获取处理code
* @return int
*/
public function getCode()
{
return $this->code;
}
/** 获取处理message
* @return string
*/
public function getMessage()
{
return $this->message;
}
/** 产生随机字符串,不长于32位
* @param int $length
* @return string
*/
public function getNonceStr($length = 32)
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#%^&*;:-=_+,.";
$str ="";
for ( $i = 0; $i < $length; $i++ ) {
$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
return $str;
}
/** 生成sha1的secret
* @other 绑定生成的 内容,secret_key,secret_id
* @return string
*/
public function signSha1Create()
{
$nonce = $this->getNonceStr();
$rand = rand();
$time = time();
$content = "The signature : nonce={$nonce}; rand={$rand}; time={$time}, by sok yo!";
//生成签名内容
file_put_contents('signature.txt', $content);
$signature = hash_hmac_file('SHA1','signature.txt','secret');
unlink('signature.txt');
return $signature;
}
/** sha1数据加密
* @param $secret_id
* @param $secret_key
* @return string
*/
public function signSha1Encrypt($secret_id,$secret_key)
{
$time = time();
// 业务逻辑,向参数列表填入参数(可抽离)
$arg_list = array(
"secretId" => $secret_id,
"currentTimeStamp" => $time,
<