PHP中 hmac_md5 加密算法

//转换字符编码为utf-8
function strToUtf8($str){
	$encode = mb_detect_encoding($str, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
	if($encode == 'UTF-8'){
		return $str;
	}
	else{
		return mb_convert_encoding($str, 'UTF-8', $encode);
	}
}

/**
 * 基于md5的加密算法hmac
 *
 * md5已经不是那么安全了,多折腾几下吧
 * 下面2种都可以用
 * @param String $data 预加密数据
 * @param String $key  密钥
 * @return String
 */
function hmac($data, $key){ 
	$data = strToUtf8($data);
	$key = strToUtf8($key);

	if (function_exists('hash_hmac')) {
		return hash_hmac('md5', $data, $key);
	}

	$key = (strlen($key) > 64) ? pack('H32', 'md5') : str_pad($key, 64, chr(0));
	$ipad = substr($key,0, 64) ^ str_repeat(chr(0x36), 64);
	$opad = substr($key,0, 64) ^ str_repeat(chr(0x5C), 64);
	return md5($opad.pack('H32', md5($ipad.$data)));
}
function hmac2($data, $key){ 
	$key = strToUtf8($key);
	$data = strToUtf8($data);

	$b = 64; // byte length for md5   
	if (strlen($key) > $b) {   
		$key = pack("H32",md5($key));   
	}   
	$key = str_pad($key, $b, chr(0x00));   
	$ipad = str_pad('', $b, chr(0x36));   
	$opad = str_pad('', $b, chr(0x5c));   
	$k_ipad = $key ^ $ipad ;   
	$k_opad = $key ^ $opad;   

	return strtoupper(md5($k_opad . pack("H32",md5($k_ipad . $data))));
}

转自:php hmac_md5 算法函数

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值