这篇文章主要为大家详细介绍了php-app开发接口加密规则,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
自己平时工作中用到的一套接口加密规则,记录下来以后用:
$xpp_key = "xxx";
//接收参数param,将结果解析json得到参数数组
$param = json_decode($_POST['param'],true);
//取出sign,去掉参数数组中的sign
$client_sign = $param['sign'];
unset($param['sign']);
//将参数数组key值按照自然排序从大到小排序
krsort($param);
//将排序后的参数数组按照key=val&key=val的形式组成字符串,将字符串与XPP_KEY连接,用md5加密一次(32位小写),得到sign
$sb = '';
foreach($param as $key=>$val){
$sb .= $key . '=' . $val . '&';
}
$sb .= $xpp_key;
$server_sign = md5($sb);
//将sign与客户端传过来的sign进行比对,如不一样则可能是中途被篡改参数,服务器拒绝此次请求
if($server_sign !== $client_sign){
echo json_encode(array('code'=>'invalid request'));
exit;
}
//将sign与session中的sign对比,如果一样,则为重复提交,服务器拒绝此次请求
if($server_sign == $_SESSION['last_sign']){
echo json_encode(array('code'=>'Repeated requests'));
exit();
}
//此次的sign存入session
$_SESSION['last_sign'] = $server_sign;
//执行路由cmd(base64解析后),将参数带到该方法中
$cmd = base64_decode($param['cmd']);
list($controller,$action) = explode('-',$cmd);
// 设置请求参数
unset($param['cmd']);
unset($param['timestamp']);
foreach($param as $key => $val){
$_REQUEST[$key] = $val;
}
客户端代码demo:
paramsMap = new HashMap();
paramsMap.put("timestamp",(System.currentTimeMillis() / 1000 + ""));
String cmd = new String(base64.encode("user-camList".getBytes()));
String dcmd = new String(base64.decode(cmd.getBytes()));
paramsMap.put("cmd",cmd);
paramsMap.put("sign",getString(paramsMap));
String str = getKeyValues(paramsMap);
paramsMap = new HashMap();
paramsMap.put("param",str);
Params params = new Params();
params.listener = this;
params.url = url;
//new NetWorkTask().executeProxy(params);
new NetPostTask(paramsMap).executeProxy(params);
}
@Override
public void onGetResult(int errorCode,Object result) {
super.onGetResult(errorCode,result);
System.out.println();
}
private String getString(Map paramsMap) {
TreeMap tm = new TreeMap(paramsMap);
Iterator i = tm.descendingMap().entrySet().iterator();
StringBuffer buffer = new StringBuffer();
while (i.hasNext()) {
buffer.append(i.next() + "&");
}
buffer.append(AppKey);
return DensityUtil.MD5(buffer.toString());
}
// 得到键值对
private String getKeyValues(Map paramsMap) {
TreeMap tm = new TreeMap(paramsMap);
Iterator i = tm.descendingKeySet().iterator();
String jsonText = JSON.toJSONString(tm.descendingMap(),true);
return jsonText;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。