Customer demand small terminal with JS generated signature, we follow the requirements step by step resolution, and the request method encapsulated into a utils.js:
The first step: the associative array is sorted by the key name in a positive order.
Step Two: stitching strings
Step three: Add the stitched string to the private key
Fourth step: Encrypt the above string MD5
Const MD5 = require (' md5.js '); var appsecret = "Appsecret"; var app_key = "App_key";//alphabetical order: Case-insensitive function Sortcharter (A, B) {if (a.tostring (). toUpperCase () > B.tostring (). toUpperCase ()) {return 1;} else if (a.tostring (). toUpperCase () = = B.tostring (). toUpperCase ()) {return 0;} else {return-1;}} function Objkeysort (obj) {//sort of var Newkey = Object.keys (obj). sort (sortcharter);//Use the keys method of the object's built-in class to get the property names of the objects to be sorted. Then using the Sort method on the array prototype to sort the obtained property names, Newkey is an array var newObj = {};//Creates a new object to hold the ordered key-value pair for (var i = 0; i < newkey.length; i++) {//Traversal Newkey array newobj[newkey[i]] = obj[newkey[i]];//to newly created objects in sorted order increase the key value to}return newobj;//return the ordered new object} String.prototype.PadLeft = function (len, charstr) {var s = this + '; return new Array (Len-s.length + 1). Join (Charstr, ' ') + S;} Create Signfunction create_sign (data) {Console.log ("1, pre-order Create_sign0"), Console.log (data),//1, sort data = Objkeysort ( Data), Console.log ("1, create_sign111 after sorting"), Console.log (data)//2. splicing var txt= ""; var Newkey = Object.keys (data); for (Var i = 0; I < Newkey.length; i++) {//traversal newkey Array txt = txt + newkey[i].length.tostring (). PadLeft (2, ' 0 '); txt=txt+ "-"; txt = txt + newkey[i];txt = txt + ":";//Console.log ("for internal ===k-v"); Console.log (Newkey[i]); c Onsole.log (data[newkey[i]); txt = txt + data[newkey[i]].tostring (). length.tostring (). PadLeft (4, ' 0 '); txt = txt + "-"; txt = txt + data[newkey[i]];if (i < (newkey.length-1)) {txt = txt + ";"}} Console.log ("for internal ===3. Append private key Appsecret");//3. Append private key appsecret//console.log (TXT);//Console.log ("appsecret=" + Appsecret); txt = txt + appsecret;//4.md5 encrypted txt = md5.hex_md5 (TXT); return txt;}
The "Go" JS object is sorted by key value (not partition case), and the signature method is generated