js模拟签名

在openapi中需要对参数进行签名,这里做了一个用js来模拟的例子,在实际应用中不能用js来做,因为会暴露secretkey,这里仅用于内部测试之用,另外散列使用md5-min.js来做。

sig.js

/// <reference path="http://www.cnblogs.com/Scripts/jquery-1.6.2-vsdoc.js" />
//
/ <reference path="http://www.cnblogs.com/Scripts/json2.js" />

/*------------------------------------*\
sig
\*------------------------------------
*/

var SIG = {

run:
function (dict, secret_key) {
dict
= SIG._sort(dict);
SIG._sigData(dict, secret_key);
return dict;
},

_sort:
function (dict) {
//提取key为数组
var _keys = [];
$.each(dict,
function (k, v) {
_keys.push(k);
});
//对key数据排序
_keys.sort(function (a, b) {
return a > b;
});
//创建新字典
var _newdict = {};
$.each(_keys,
function (i, v) {
_newdict[v]
= dict[v];
});
return _newdict;
},

_sigData:
function (dict, secret_key) {

//1、key排序
//2、生成sig
//3、组合sig到json
var sigtext = SIG._getSigText(dict, secret_key);
dict[
'sig'] = sigtext;
},

_getSigText:
function (dict, secretkey) {
var html = [];
$.each(dict,
function (k, v) {
html.push(k,
'=', v);
});
html.push(secretkey);
var plaintext = (html.join(''));
var sigtext = hex_md5(plaintext);

return sigtext
}


}

post test

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>StoreToken</title>
<!--<script src="http://www.cnblogs.com/Scripts/jquery-1.6.2-vsdoc.js" type="text/javascript"></script>-->
<script src="http://www.cnblogs.com/Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/json2.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/md5-min.js" type="text/javascript"></script>
<script src="sig.js" type="text/javascript"></script>
<script type="text/javascript">

$(
function () {

var postdata = SIG.run(
{
"api_key": "11111111111111111111111111111111",
"call_id": new Date().getTime(),
"method": "push.storeToken",
"v": "1",
"token": "123"
},
'88888888888888888888888888888888');

$(
"<p />").html(JSON.stringify(postdata)).appendTo($('#msgbox'));

$.post(
"/service", postdata, function (data, textStatus) {
if (textStatus == "success") {
$(
"<p />").html(JSON.stringify(data)).appendTo($('#msgbox'));
if (data != null) {
}
else {
alert(
"调用不成功");
}
}
else {
alert(
"textStatus: " + textStatus);
}
});
});
</script>
</head>
<body>
<div id="msgbox">
</div>
</body>
</html>

  

posted @ 2011-08-06 22:02  chenjunbiao  阅读(757)  评论(0编辑  收藏  举报