最近准备接入阿里云物联网套件,在接入mqtt协议的过程中需要用到hmacsha1算法加密
php的hmacsha1加密算法如下
/*
* @使用HMAC-SHA1算法生成阿里云签名值
*
* @param $key 密钥
* @param $str 源串
*
* @return 签名值
*/
function hmacsha1($str, $key)
{
$signature = "";
if (function_exists('hash_hmac'))
{
$signature = hash_hmac("sha1", $str, $key, true);
}
else
{
$blocksize = 64;
$hashfunc = 'sha1';
if (strlen($key) > $blocksize)
{
$key = pack('H*', $hashfunc($key));
}
$key = str_pad($key,$blocksize,chr(0x00));
$ipad = str_repeat(chr(0x36),$blocksize);
$opad = str_repeat(chr(0x5c),$blocksize);
$hmac = pack(
'H*',$hashfunc(
($key^$opad).pack(
'H*',$hashfunc(
($key^$ipad).$str
)
)
)
);
$signature = $hmac;
}
return $signature;
}
阿里云还要求把签名转换成十六进制
在php中可以使用bin2hex函数把二进制内容转成十六进制
另附上hmacmd5加密算法
/**
*
* @param $key 密钥
* @param $data 源串
*
* @return 签名值
*/
function HmacMd5($data,$key){
if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key);
}
//RFC 2104 HMAC implementation for php
//Creates an md5 HMAC.
//Eliminates the need to install mhash to compute a HMAC
//Hacked by Lance Rushing(NOTE:Hacked means written)
//需要配置环境支持iconv,否则中文参数不能正常处理
$key = iconv("GB2312","UTF-8",$key);
$data= iconv("GB2312","UTF-8",$data);
$b=64;
if(strlen($key)>$b){
$key = pack("H*",md5($key));
}
$key= str_pad($key,$b,chr(0x00));
$ipad = str_pad('',$b,chr(0x36));
$opad=str_pad('',$b,chr(ox5c));
$k_ipad = $key^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad.pack("H*",md5($k_ipad.$data)));
}