1. 程式人生 > >微信小程序 使用HMACSHA1和md5為登陸註冊報文添加指紋驗證簽名

微信小程序 使用HMACSHA1和md5為登陸註冊報文添加指紋驗證簽名

wide dea ini nco sca typeof npr mage 防止

對接口請求報文作指紋驗證簽名相信在開發中經常碰到,

這次在與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 [[email protected]]
 * @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
// }
View Code

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 }
View Code

微信小程序 使用HMACSHA1和md5為登陸註冊報文添加指紋驗證簽名