微信小程序 使用HMACSHA1和md5为登陆注册报文添加指纹验证签名
对接口请求报文作指纹验证签名相信在开发中经常碰到,
这次在与java后端一起开发小程序时,就碰到需求对登陆注册请求报文添加指纹验证签名来防止信息被修改
先来看下我们与后端定制签名规则
2.4. 签名规则
原文规则:采用标准的JSON格式,null值字段舍去,按照key值字符串升序排列 例如:{"appId":"1100310061380986","outTradeNo":"1515120685073","timestamp":1516947786,"tradeNo":"S2018010510512529274450746","version":"1.0"}
加密规则: 先将原文用HMACSHA1加密,加密秘钥为appkey,加密后将字节数组转换为十六进制字符A;然后再将A用MD5加密得到签名,此时上送报文:{"appId":"1100310061380986","outTradeNo":"1515120685073","sign":"0799322CC44C7B7F6DC2CEA1DD588A6876889950E540B49CC5ECE6660AFD24224BEB04C79BA5C7F894E4223AE1BB59CC","timestamp":1516947786,"tradeNo":"S2018010510512529274450746","version":"1.0"}
让我们来整理下整个报文加密签名的流程
1,在app.js定义好各种公用参数,以方便在组装接口数据时统一调用
如:
globalData: { //全局变量 appid: '11**17356***', //appid version: '1.0',//版本号 sign: '',//签名 validateWay: 1, //验证码接口:验证方式 1:短信 validateType: 2, ///验证码接口:功能类型 1注册 2 登录 appkey: 'f***05fffe44540***fde6d4a***', //加密所需的key值 loginChannel: '1003',//登录渠道:1001 ios手机 1002 android手机 1003 微信小程序 1004 手机H5 loginDevice: 'W',//ios手机前缀“I” android手机前缀“A”微信小程序前缀“W” 手机H5前缀“C” url: 'http://sf**gq.n**ee.cc' }
2,在util.js中封装加密规则方法,以方便在组装接口数据时调用
如:
function encryption(key,value){ //封闭全局加密方法 // console.log('明文:', key, value); var val = value; console.log('明文:',val); var jsonstr = objKeySort(val); console.log("排序后:",jsonstr); jsonstr = JSON.stringify(jsonstr); console.log('对象转字符串后:',jsonstr); // console.log(typeof (jsonstr)) val = jsonstr; var sha1 = require('js/sha1.js'); var sha1Pw = sha1.HmacSHA1(val, key); //sha1加密 val = sha1Pw.toString(); console.log('sha1加密:', val); var md5 = require('js/md5.js'); //md5加密 var md5Pw = md5.hexMD5(val); console.log('md5加密:', md5Pw); return md5Pw; } //排序的函数 function objKeySort(obj) {//排序的函数 var newkey = Object.keys(obj).sort(); //先用Object内置类的keys方法获取要排序对象的属性名,再利用Array原型上的sort方法对获取的属性名进行排序,newkey是一个数组 var newObj = {};//创建一个新的对象,用于存放排好序的键值对 for (var i = 0; i < newkey.length; i++) {//遍历newkey数组 newObj[newkey[i]] = obj[newkey[i]];//向新创建的对象中按照排好的顺序依次增加键值对 } return newObj;//返回排好序的新对象 } module.exports = { //formatTime: formatTime, // Bytes2Str: Bytes2Str, // Str2Bytes: Str2Bytes, encryption: encryption }
3,组装接口报文【调用方法前,先引用app.js和util.js】
const utils = require('../../utils/util.js') const apps = require('../../app.js') var app = getApp(); Page({ 。。。 showTopTips:function(e){ //登录/注册提交事件 if (this.data.mobile==''){ app.toastShow(this, "请输入手机号", "error"); } else if (this.data.validateCode==''){ app.toastShow(this, "请输入验证码", "error"); }else{ var that = this wx.login({//调用获取用户openId success: function (res) { var loginDevice = getApp().globalData.loginDevice; //唯一标识 = W + 用户名 loginDevice = loginDevice + res.code //临时code值 var appid = getApp().globalData.appid; //appid var timestamp = Date.parse(new Date());//获取当前时间戳 timestamp = timestamp / 1000; var version = getApp().globalData.version; //版本号 var sign = getApp().globalData.sign; //签名 var mobile = that.data.mobile; var validateCode = that.data.validateCode; //手持设备标识 var loginChannel = getApp().globalData.loginChannel; //登录渠道:1001 ios手机 1002 android手机 1003 微信小程序 1004 手机H5 var data = {"appId": appid,"timestamp": timestamp,"version":version,"mobile": mobile,"validateCode": validateCode, "loginChannel":loginChannel, "loginDevice": loginDevice}; var url = getApp().globalData.url; //接口路径 var key = getApp().globalData.appkey; //加密k值 var encryption = utils.encryption(key, data) //算出签名 sign = encryption;//赋值给签名 data.sign = sign; data = JSON.stringify(data); // console.log('算出签名的data结果:', data) wx.request({ method: "post", url: url+'/user/baseInfo/userLogin', //登录/注册 data: data + '@#@' + appid, dataType: "json", header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { // debugger; console.log('注册/登录信息',res); if (res.data.code == '0000') { var userIdEnc = res.data.data.userIdEnc; var loginDevice = res.data.data.loginDevice; console.log('请求成功后赋值--', 'userIdEnc:', userIdEnc, 'loginDevice:', loginDevice); wx.setStorage({ key: 'userIdEnc', data: userIdEnc, success: function (res) { console.log("用户唯一标识存入缓存成功", res) }, fail: function (res) { console.log("用户唯一标识存入缓存成功", res) } }) wx.setStorage({ key: 'loginDevice', data: loginDevice, success: function (res) { console.log("用户唯一标识存入缓存成功", res) }, fail: function (res) { console.log("用户唯一标识存入缓存失败", res) } }) that.redirectToIndex(); // console.log("loginDevice1111111",userIdEnc) } else if (res.data.code == '1002') { //超时 that.errorShow('超时'); } else if (res.data.code == '1002') { //帐号冻结 that.errorShow('帐号冻结'); } else if (res.data.code == '2006') { //已在其他设备上登录 var userIdEnc = res.data.data.userIdEnc; var loginDevice = res.data.data.loginDevice; console.log('请求成功后赋值--', 'userIdEnc:', userIdEnc, 'loginDevice:', loginDevice); //将后台返回的用户唯一标识存入本地缓存中 wx.setStorage({ key: 'userIdEnc', data: userIdEnc, success: function (res) { console.log("用户唯一标识存入缓存成功", res) }, fail: function (res){ console.log("用户唯一标识存入缓存失败", res) } }) wx.setStorage({ key: 'loginDevice', data: loginDevice, success: function (res) { console.log("用户唯一标识存入缓存成功", res) }, fail: function (res) { console.log("用户唯一标识存入缓存成功", res) } }) that.redirectToIndex(); console.log("登录成功",userIdEnc) } else if (res.data.code == '2005') { //手机未注册 that.errorShow('手机未注册'); } else if (res.data.code == '2002') { //动态验证码错误或已失效 that.errorShow('动态验证码错误或已失效'); } else if (res.data.code == '1000') { //系统异常 that.errorShow('系统异常'); }else { //失败 that.errorShow('注册/登录失败1'); } }, fail: function (res) { that.errorShow('注册/登录失败2'); //console.log(res.data); console.log('is failed') } }) }, fail: function (res) { console.log('获取临时code失败!' + res.errMsg) } }) } },
errorShow: function (error) { //统一调用错误提醒tips
wx.showToast({
title: error,
icon: 'error',
image: '../../images/error.png',
duration: 2000
})
}, redirectToIndex:function(){ //统一跳转到首页
wx.redirectTo({
url: '../../pages/index/index',
})
}
})
到此大功告成!
附上本次所用加密文件源码,计算结果与java方法结果一样!
sha1.js
/* * [js-sha1]{} * * @version 0.6.0 * @author H, J-C [hjc_code@126.com] * @copyright H, J-C 2018-9-28 * @license MIT */ var CryptoJS = CryptoJS || function (g, l) { var e = {}, d = e.lib = {}, m = function () { }, k = d.Base = { extend: function (a) { m.prototype = this; var c = new m; a && c.mixIn(a); c.hasOwnProperty("init") || (c.init = function () { c.$super.init.apply(this, arguments) }); c.init.prototype = c; c.$super = this; return c }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, p = d.WordArray = k.extend({ init: function (a, c) { a = this.words = a || []; this.sigBytes = c != l ? c : 4 * a.length }, toString: function (a) { return (a || n).stringify(this) }, concat: function (a) { var c = this.words, q = a.words, f = this.sigBytes; a = a.sigBytes; this.clamp(); if (f % 4) for (var b = 0; b < a; b++) c[f + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((f + b) % 4); else if (65535 < q.length) for (b = 0; b < a; b += 4) c[f + b >>> 2] = q[b >>> 2]; else c.push.apply(c, q); this.sigBytes += a; return this }, clamp: function () { var a = this.words, c = this.sigBytes; a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4); a.length = g.ceil(c / 4) }, clone: function () { var a = k.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var c = [], b = 0; b < a; b += 4) c.push(4294967296 * g.random() | 0); return new p.init(c, a) } }), b = e.enc = {}, n = b.Hex = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], f = 0; f < a; f++) { var d = c[f >>> 2] >>> 24 - 8 * (f % 4) & 255; b.push((d >>> 4).toString(16)); b.push((d & 15).toString(16)) } return b.join("") }, parse: function (a) { for (var c = a.length, b = [], f = 0; f < c; f += 2) b[f >>> 3] |= parseInt(a.substr(f, 2), 16) << 24 - 4 * (f % 8); return new p.init(b, c / 2) } }, j = b.Latin1 = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], f = 0; f < a; f++) b.push(String.fromCharCode(c[f >>> 2] >>> 24 - 8 * (f % 4) & 255)); return b.join("") }, parse: function (a) { for (var c = a.length, b = [], f = 0; f < c; f++) b[f >>> 2] |= (a.charCodeAt(f) & 255) << 24 - 8 * (f % 4); return new p.init(b, c) } }, h = b.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(j.stringify(a))) } catch (c) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return j.parse(unescape(encodeURIComponent(a))) } }, r = d.BufferedBlockAlgorithm = k.extend({ reset: function () { this._data = new p.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = h.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var c = this._data, b = c.words, f = c.sigBytes, d = this.blockSize, e = f / (4 * d), e = a ? g.ceil(e) : g.max((e | 0) - this._minBufferSize, 0); a = e * d; f = g.min(4 * a, f); if (a) { for (var k = 0; k < a; k += d) this._doProcessBlock(b, k); k = b.splice(0, a); c.sigBytes -= f } return new p.init(k, f) }, clone: function () { var a = k.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); d.Hasher = r.extend({ cfg: k.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { r.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (b, d) { return (new a.init(d)).finalize(b) } }, _createHmacHelper: function (a) { return function (b, d) { return (new s.HMAC.init(a, d)).finalize(b) } } }); var s = e.algo = {}; return e }(Math); (function () { var g = CryptoJS, l = g.lib, e = l.WordArray, d = l.Hasher, m = [], l = g.algo.SHA1 = d.extend({ _doReset: function () { this._hash = new e.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (d, e) { for (var b = this._hash.words, n = b[0], j = b[1], h = b[2], g = b[3], l = b[4], a = 0; 80 > a; a++) { if (16 > a) m[a] = d[e + a] | 0; else { var c = m[a - 3] ^ m[a - 8] ^ m[a - 14] ^ m[a - 16]; m[a] = c << 1 | c >>> 31 } c = (n << 5 | n >>> 27) + l + m[a]; c = 20 > a ? c + ((j & h | ~j & g) + 1518500249) : 40 > a ? c + ((j ^ h ^ g) + 1859775393) : 60 > a ? c + ((j & h | j & g | h & g) - 1894007588) : c + ((j ^ h ^ g) - 899497514); l = g; g = h; h = j << 30 | j >>> 2; j = n; n = c } b[0] = b[0] + n | 0; b[1] = b[1] + j | 0; b[2] = b[2] + h | 0; b[3] = b[3] + g | 0; b[4] = b[4] + l | 0 }, _doFinalize: function () { var d = this._data, e = d.words, b = 8 * this._nDataBytes, g = 8 * d.sigBytes; e[g >>> 5] |= 128 << 24 - g % 32; e[(g + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296); e[(g + 64 >>> 9 << 4) + 15] = b; d.sigBytes = 4 * e.length; this._process(); return this._hash }, clone: function () { var e = d.clone.call(this); e._hash = this._hash.clone(); return e } }); g.SHA1 = d._createHelper(l); g.HmacSHA1 = d._createHmacHelper(l) })(); (function () { var g = CryptoJS, l = g.enc.Utf8; g.algo.HMAC = g.lib.Base.extend({ init: function (e, d) { e = this._hasher = new e.init; "string" == typeof d && (d = l.parse(d)); var g = e.blockSize, k = 4 * g; d.sigBytes > k && (d = e.finalize(d)); d.clamp(); for (var p = this._oKey = d.clone(), b = this._iKey = d.clone(), n = p.words, j = b.words, h = 0; h < g; h++) n[h] ^= 1549556828, j[h] ^= 909522486; p.sigBytes = b.sigBytes = k; this.reset() }, reset: function () { var e = this._hasher; e.reset(); e.update(this._iKey) }, update: function (e) { this._hasher.update(e); return this }, finalize: function (e) { var d = this._hasher; e = d.finalize(e); d.reset(); return d.finalize(this._oKey.clone().concat(e)) } }) })(); //使用算法 // var key = "f7205fffe445408a848eae6fde6d4acf" // var sha1_result = CryptoJS.HmacSHA1("18621053227", key) // console.log('-------',sha1_result.toString()) module.exports = CryptoJS; // module.exports = { // sha1: CryptoJS.HmacSHA1 // }
md5.js
/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 1.1 Copyright (C) Paul Johnston 1999 - 2002. * Code also contributed by Greg Holt * See http://pajhome.org.uk/site/legal.html for details. */ /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF) var msw = (x >> 16) + (y >> 16) + (lsw >> 16) return (msw << 16) | (lsw & 0xFFFF) } /* * Bitwise rotate a 32-bit number to the left. */ function rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)) } /* * These functions implement the four basic operations the algorithm uses. */ function cmn(q, a, b, x, s, t) { return safe_add(rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) } function ff(a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t) } function gg(a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t) } function hh(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t) } function ii(a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t) } /* * Calculate the MD5 of an array of little-endian words, producing an array * of little-endian words. */ function coreMD5(x) { var a = 1732584193 var b = -271733879 var c = -1732584194 var d = 271733878 for (var i = 0; i < x.length; i += 16) { var olda = a var oldb = b var oldc = c var oldd = d a = ff(a, b, c, d, x[i + 0], 7, -680876936) d = ff(d, a, b, c, x[i + 1], 12, -389564586) c = ff(c, d, a, b, x[i + 2], 17, 606105819) b = ff(b, c, d, a, x[i + 3], 22, -1044525330) a = ff(a, b, c, d, x[i + 4], 7, -176418897) d = ff(d, a, b, c, x[i + 5], 12, 1200080426) c = ff(c, d, a, b, x[i + 6], 17, -1473231341) b = ff(b, c, d, a, x[i + 7], 22, -45705983) a = ff(a, b, c, d, x[i + 8], 7, 1770035416) d = ff(d, a, b, c, x[i + 9], 12, -1958414417) c = ff(c, d, a, b, x[i + 10], 17, -42063) b = ff(b, c, d, a, x[i + 11], 22, -1990404162) a = ff(a, b, c, d, x[i + 12], 7, 1804603682) d = ff(d, a, b, c, x[i + 13], 12, -40341101) c = ff(c, d, a, b, x[i + 14], 17, -1502002290) b = ff(b, c, d, a, x[i + 15], 22, 1236535329) a = gg(a, b, c, d, x[i + 1], 5, -165796510) d = gg(d, a, b, c, x[i + 6], 9, -1069501632) c = gg(c, d, a, b, x[i + 11], 14, 643717713) b = gg(b, c, d, a, x[i + 0], 20, -373897302) a = gg(a, b, c, d, x[i + 5], 5, -701558691) d = gg(d, a, b, c, x[i + 10], 9, 38016083) c = gg(c, d, a, b, x[i + 15], 14, -660478335) b = gg(b, c, d, a, x[i + 4], 20, -405537848) a = gg(a, b, c, d, x[i + 9], 5, 568446438) d = gg(d, a, b, c, x[i + 14], 9, -1019803690) c = gg(c, d, a, b, x[i + 3], 14, -187363961) b = gg(b, c, d, a, x[i + 8], 20, 1163531501) a = gg(a, b, c, d, x[i + 13], 5, -1444681467) d = gg(d, a, b, c, x[i + 2], 9, -51403784) c = gg(c, d, a, b, x[i + 7], 14, 1735328473) b = gg(b, c, d, a, x[i + 12], 20, -1926607734) a = hh(a, b, c, d, x[i + 5], 4, -378558) d = hh(d, a, b, c, x[i + 8], 11, -2022574463) c = hh(c, d, a, b, x[i + 11], 16, 1839030562) b = hh(b, c, d, a, x[i + 14], 23, -35309556) a = hh(a, b, c, d, x[i + 1], 4, -1530992060) d = hh(d, a, b, c, x[i + 4], 11, 1272893353) c = hh(c, d, a, b, x[i + 7], 16, -155497632) b = hh(b, c, d, a, x[i + 10], 23, -1094730640) a = hh(a, b, c, d, x[i + 13], 4, 681279174) d = hh(d, a, b, c, x[i + 0], 11, -358537222) c = hh(c, d, a, b, x[i + 3], 16, -722521979) b = hh(b, c, d, a, x[i + 6], 23, 76029189) a = hh(a, b, c, d, x[i + 9], 4, -640364487) d = hh(d, a, b, c, x[i + 12], 11, -421815835) c = hh(c, d, a, b, x[i + 15], 16, 530742520) b = hh(b, c, d, a, x[i + 2], 23, -995338651) a = ii(a, b, c, d, x[i + 0], 6, -198630844) d = ii(d, a, b, c, x[i + 7], 10, 1126891415) c = ii(c, d, a, b, x[i + 14], 15, -1416354905) b = ii(b, c, d, a, x[i + 5], 21, -57434055) a = ii(a, b, c, d, x[i + 12], 6, 1700485571) d = ii(d, a, b, c, x[i + 3], 10, -1894986606) c = ii(c, d, a, b, x[i + 10], 15, -1051523) b = ii(b, c, d, a, x[i + 1], 21, -2054922799) a = ii(a, b, c, d, x[i + 8], 6, 1873313359) d = ii(d, a, b, c, x[i + 15], 10, -30611744) c = ii(c, d, a, b, x[i + 6], 15, -1560198380) b = ii(b, c, d, a, x[i + 13], 21, 1309151649) a = ii(a, b, c, d, x[i + 4], 6, -145523070) d = ii(d, a, b, c, x[i + 11], 10, -1120210379) c = ii(c, d, a, b, x[i + 2], 15, 718787259) b = ii(b, c, d, a, x[i + 9], 21, -343485551) a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) } return [a, b, c, d] } /* * Convert an array of little-endian words to a hex string. */ function binl2hex(binarray) { var hex_tab = "0123456789abcdef" var str = "" for (var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF) } return str } /* * Convert an array of little-endian words to a base64 encoded string. */ function binl2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" var str = "" for (var i = 0; i < binarray.length * 32; i += 6) { str += tab.charAt(((binarray[i >> 5] << (i % 32)) & 0x3F) | ((binarray[i >> 5 + 1] >> (32 - i % 32)) & 0x3F)) } return str } /* * Convert an 8-bit character string to a sequence of 16-word blocks, stored * as an array, and append appropriate padding for MD4/5 calculation. * If any of the characters are >255, the high byte is silently ignored. */ function str2binl(str) { var nblk = ((str.length + 8) >> 6) + 1 // number of 16-word blocks var blks = new Array(nblk * 16) for (var i = 0; i < nblk * 16; i++) blks[i] = 0 for (var i = 0; i < str.length; i++) blks[i >> 2] |= (str.charCodeAt(i) & 0xFF) << ((i % 4) * 8) blks[i >> 2] |= 0x80 << ((i % 4) * 8) blks[nblk * 16 - 2] = str.length * 8 return blks } /* * Convert a wide-character string to a sequence of 16-word blocks, stored as * an array, and append appropriate padding for MD4/5 calculation. */ function strw2binl(str) { var nblk = ((str.length + 4) >> 5) + 1 // number of 16-word blocks var blks = new Array(nblk * 16) for (var i = 0; i < nblk * 16; i++) blks[i] = 0 for (var i = 0; i < str.length; i++) blks[i >> 1] |= str.charCodeAt(i) << ((i % 2) * 16) blks[i >> 1] |= 0x80 << ((i % 2) * 16) blks[nblk * 16 - 2] = str.length * 16 return blks } /* * External interface */ function hexMD5(str) { return binl2hex(coreMD5(str2binl(str))) } function hexMD5w(str) { return binl2hex(coreMD5(strw2binl(str))) } function b64MD5(str) { return binl2b64(coreMD5(str2binl(str))) } function b64MD5w(str) { return binl2b64(coreMD5(strw2binl(str))) } /* Backward compatibility */ function calcMD5(str) { return binl2hex(coreMD5(str2binl(str))) } module.exports = { hexMD5: hexMD5 }