最近小程序需求一个签名加密,要把请求参数按键值排序并转化为字符串,然后进行MD5加密。
//时间戳 var timestamp = (Date.parse(new Date()))/1000;//签名验证 var key = \'服务端给的\'; var json = { signTime: timestamp, versionNumber: that.data.versionNumber, title: name, idcard: cardnum, limit: that.data.limit, page: that.data.page, } //json转换为数组并按键值升序排列再转化为字符串 let { keys, values, entries } = Object; let dataArr = []; //json的每个属性和值添加到数组 for (let [key, value] of entries(json)) { dataArr.push([key + value]); } var newStr = dataArr.sort().join(""); //数组排序并转化为字符串 console.log(newStr); var sign = key + newStr + key; sign = MD5(sign).toUpperCase(); //MD5加密并转为大写 console.log(sign);
思路是先把json格式的数据的每项参数和属性都添加到一个数组,然后把数组排序,再转为字符串,最后进行MD5加密。
后来觉得有点麻烦,直接新建数组,然后排序转为字符串,再进行MD5加密。
var arr = [\'signTime\' + timestamp, \'versionNumber\' + that.data.versionNumber, \'title\' + that.name, \'idcard\' + that.cardnum, \'limit\' + that.data.limit, \'page\' + that.data.page]; var newArr = []; for (var i = 0; i < arr.length; i++){ newArr.push(arr[i]); } console.log(newArr); var newStr = newArr.sort().join(""); //数组排序并转化为字符串 console.log(newStr); var sign = key + newStr + key;
现在基本所有接口都要签名,所以直接写了一个简单全局的方法,方便调用。
全局方法:
makeSign:function (obj) { var key = \'你的key\'; var timestamp = (Date.parse(new Date()))/1000; var versionNumber = \'app-v1\'; obj["versionNumber"] = versionNumber; obj["signTime"] = timestamp; let { keys, values, entries } = Object; let dataArr = []; //obj的每个属性和值添加到数组 for (let [key, value] of entries(obj)) { dataArr.push([key + value]); } var newStr = dataArr.sort().join(""); //数组排序并转化为字符串 var sign = key + newStr + key; sign = MD5(sign).toUpperCase(); //MD5加密并转为大写 return sign; }
调用:
var obj = { //必传参数 具体看公司规定 } obj.sign = app.makeSign(obj); //把签名添加到obj里 var data = obj; //获取分类信息 wx.request({ url: api.wx.Url, data: data, method: \'Get\', header: { \'content-type\': \'application/x-www-form-urlencoded\' }, // 设置请求的 header success: (res) => { console.log(res); ...... } })
大神的通用方法:
const upperFirst = function (word) { return word[0].toUpperCase() + word.slice(1); } const isType = function (obj, type) { return type ? toString.call(obj) === \'[object \' + upperFirst(type) + \']\' : toString.call(obj).match(/(?![\[object ]).*(?=\])/i)[0].toLowerCase(); }; const getSign = function (params) { if (!params) { params = {} } var bandParam = "key"; var versionNumber = "web-v1"; params["versionNumber"] = versionNumber; params["signTime"] = (new Date().getTime() / 1000).toFixed(0); var newData = Object.keys(params).sort(); var sign = bandParam; for (let key of newData) { var item = params[key]; if (isType(item, "array") || isType(item, "object" || key == "sign")) { return; } sign += key + item; } sign += bandParam; params["sign"] = MD5(sign).toUpperCase(); return params; }
调用:
data: getSign({ //必填参数 }),