通常情况下,这种很长一段数字字母的key和secret都是通过md5和sha1加密算法来生成的
appkey的生成
appkey生成比较简单,一般是客户的唯一值+字符串组成,方法很多,做到唯一性的字符串就可以。比如使用用户的uid+”abc”字符串组成。
appSecret生成方法
其原始数据有可能是你的账号的id,还有注册时间之类的唯一值进行组合再通过md5和sha1来生成,而md5和sha1对比的话,md5比sha1更快,但sha1比md5强度更高,所以在此类授权应用里,通常都使用sha1算法,例如oauth的签名算法
验证授权
例如要和微信通信里,要传递三个参数ABC,则需要将ABC与appsecret一起sha1一遍,得到一个签名串,然后将这个签名串与appkey一起传递给微信,
此时,微信会通过appkey去查找对应的appsecret,然后再将ABC参数与查询出来的appsecret做一遍相同的签名算法,如果得到的签名串一致,则认为是授权成功
如下的代码可以参考:
public function test(){
if(!isset($_GET['token'])){
$this->apiReturn(4001,'invalid token');
}else if(!S($_GET['token'])){
$this->apiReturn(4001,'invalid token');
}
$data = array(
'id'=>2,
'username'=>'明之暗夜',
'info'=>array('age'=>24,'address'=>'学府路','url'=>'http://cnblogs.com/dmm888'));
if($data){
$this->apiReturn(200,'读取用户信息成功',$data,xml);
}
}
public function getToken(){
$ori_str = S($this->appid.'_'.$this->appsecret);
//这里appid和appsecret我写固定了,实际是通过客户端获取 所以这里我们可以做很多 比如判断appid和appsecret有效性等
if($ori_str){//重新获取就把以前的token删除
S($ori_str,null);
}
//这里是token产生的机制 您也可以自己定义
$nonce = $this->createNoncestr(32);
$tmpArr = array($nonce,$this->appid,$this->appsecret);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
// echo $tmpStr;
//这里做了缓存 'a'=>b 和'b'=>a格式的缓存
S($this->appid.'_'.$this->appsecret,$tmpStr,7200);
S($tmpStr,$this->appid.'_'.$this->appsecret,7200);
}
/**
* 作用:产生随机字符串,不长于32位
*/
function createNoncestr( $length = 32 )
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789"; $str ="";
for ( $i = 0; $i < $length; $i++ ) {
$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
return $str;
}