Brief Introduction when an application sends an OpenAPI call request based on an http post or HTTPGET request, in order to ensure secure communication between the application and the REST server and prevent malicious attacks such as SecretKey theft and data tampering, the REST server uses the parameter signature mechanism. Before calling OpenAPI, an application must calculate an MD5 Signature for all its request parameters and
Brief Introduction when an application sends an Open API call request based on an http post or http get request, in order to ensure secure communication between the application and the REST server and prevent malicious attacks such as Secret Key theft and data tampering, the REST server uses the parameter signature mechanism. Before calling an Open API, an application must calculate an MD5 Signature for all its request parameters and
Introduction
When an application sends an Open API call request based on an http post or http get request, in order to ensure secure communication between the application and the REST server and prevent malicious attacks such as Secret Key theft and data tampering, the REST server uses the parameter signature mechanism. Before calling an Open API, an application needs to calculate an MD5 Signature for all its request parameters and append it to the request parameters. The parameter name is "sign ". When receiving the request, the REST server recalculates the signature and determines whether the value is consistent with the value of the sign parameter passed by the application, to determine whether the current Open API call request is forged or tampered with by a third party.
Before calling an Open API, an application must use the OAuth2.0 service to obtain authorization from the user or platform. After obtaining authorization, the application will obtain the following three important parameters:
- Access_token:The Access Authorization code required to call Open APIs over https;
- Session_key:The Access Authorization code required to call an Open API over http;
- Session_secret:Calculate the signature key used for Parameter Signatures when calling Open APIs over http.
Session_secret is the signature key required for parameter signature. This is slightly different from platforms such as Facebook and Renren. The two platforms generally use two signature keys for Parameter Signatures:
- If you use the application server to call Open APIs, the application Key (API Key) obtained during application registration is the parameter signature Key;
- If the Open API is called through client languages such as JavaScript and ActionScript, the Session Secret obtained by the application after the user authorization is the parameter signature key. Of course, Session Secret can also be used as the signature key when an Open API is called through the server.
Signature Algorithm
Assume that the request parameters involved in parameter signature calculation are "k1", "k2", and "k3", and their values are "v1", "v2", and "v3", respectively ", the parameter signature calculation method is as follows:
- Format the Request Parameters in "key = value" format, that is, "k1 = v1", "k2 = v2", and "k3 = v3 ";
- Sort the formatted parameter key-value pairs in alphabetical Ascending Order and splice them together, that is, "k1 = v1k2 = v2k3 = v3 ";
- The session_secret parameter value obtained when the Access Token is obtained through the OAuth2.0 protocol on the append of the concatenated string;
- The MD5 value of the preceding string is the signature value.
Note: do not include the sign parameter in the request parameters when calculating the signature, because the value of the sign parameter is unknown and is to be calculated..
In addition, you do not need to urlencode the parameters when calculating the signature ("application/x-www-form-urlencoded" encoding), but you need to urlencode the request when sending it, this is the easiest place for many developers to make mistakes.
Signature process example
Assume that an application needs to obtain the basic information of a user whose uid is 67411167. The session_key and session_secret parameters obtained by the application in the previous process of obtaining Access Token through OAuth2.0 are as follows:
- Session_key:"Region ="
- Session_secret:"27e1be4fdcaa83d7f61c489994ff6ed6"
The system time when the Open API is called (date ('Y-m-d H: I: s' in PHP) is "17:18:09 ", the REST server is expected to return the call result in JSON format, that is, the set of Request Parameters Involved in parameter signature calculation is:
[ "session_key" => "9XNNXe66zOlSassjSKD5gry9BiN61IUEi8IpJmjBwvU07RXP0J3c4GnhZR3GKhMHa1A=", "timestamp" => "2011-06-21 17:18:09", "format" => "json", "uid" => 67411167]
The signature calculation process is as follows:
- Format the Request Parameters in the format of "key = value". The formatted set of request parameters is:
[ "session_key=9XNNXe66zOlSassjSKD5gry9BiN61IUEi8IpJmjBwvU07RXP0J3c4GnhZR3GKhMHa1A=", "timestamp=2011-06-21 17:18:09", "format=json", "uid=67411167" ]
- Sort the formatted parameter key-value pairs in lexicographically ascending order to obtain the following parameter set:
[ "format=json", "session_key=9XNNXe66zOlSassjSKD5gry9BiN61IUEi8IpJmjBwvU07RXP0J3c4GnhZR3GKhMHa1A=", "timestamp=2011-06-21 17:18:09", "uid=67411167" ]
- Splice the preceding sorted parameter sets to obtain the following string:
format=jsonsession_key=9XNNXe66zOlSassjSKD5gry9BiN61IUEi8IpJmjBwvU07RXP0J3c4GnhZR3GKhMHa1A=timestamp=2011-06-21 17:18:09uid=67411167
- The session_secret parameter value obtained when the Access Token is obtained through the OAuth2.0 protocol is appended to the end of the concatenated string. The following string is obtained:
format=jsonsession_key=9XNNXe66zOlSassjSKD5gry9BiN61IUEi8IpJmjBwvU07RXP0J3c4GnhZR3GKhMHa1A=timestamp=2011-06-21 17:18:09uid=6741116727e1be4fdcaa83d7f61c489994ff6ed6
- Calculate the MD5 Signature for the preceding string.D24dd357a95a2579c410b3a92495f009Is required to call the API.SignParameter value.
Next, you can request the REST server of Open API through the http post method or http get method, and call the interface, for example:
GET/restful/2.0/passport/users/getInfo? Session_key = %% 3D & timestamp = 2011-06-21 + 17% 3A18% 3A09 & format = json & uid = 67411167 & sign = d24dd357a95a2579c410b3a92495f009 HTTP/1.1 Host: openapi. baidu. comUser-Agent: Client of Baidu Open PlatformAccept: */* Accept-Encoding: gzip, deflateAccept-Charset: utf-8Connection: close or POST/rest/2.0/passport/users/getInfo HTTP/1.1 Host: openapi. baidu. comUser-Agent: Client of Baidu Open PlatformAccept: */* Accept-Encoding: gzip, deflateAccept-Charset: utf-8Content-Length: 179 Connection: close session_key = %% 3D & timestamp = 2011-06-21 + 17% 3A18% 3A09 & format = json & uid = 67411167 & sign = d24dd357a95a2579c410b3a92495f009
Signature Algorithm Implementation Code PHP code implementation
The PHP code implementation method for getting a signature is as follows:
/*** Signature generation algorithm ** @ param array $ an array associated with the request parameter set called by the params API, the key that does not contain the sign parameter * @ param string $ secret signature is the session secret returned when the access token is obtained * @ return string returns the parameter signature value */function getSignature ($ params, $ secret) {$ str = ''; // string to be signed // sort the parameters in the lexicographically Ascending Order ($ params ); // traverse each key/value pair in the sorted parameter array foreach ($ params as $ k => $ v) {// generate a string in key = value format for the key/value pair and splice it into the string to be signed $ str. = "$ k = $ v";} // Concatenates the signature key to the end of the signature string $ str. = $ secret; // generate an md5 Signature for the signature string using the md5 algorithm. The signature is the sign parameter value to be appended: return md5 ($ str );}
Call example:
$uid = 67411167;$params = array( "session_key" => "9XNNXe66zOlSassjSKD5gry9BiN61IUEi8IpJmjBwvU07RXP0J3c4GnhZR3GKhMHa1A=", "timestamp" => "2011-06-21 17:18:09", "format" => "json", "uid" => $uid,);$sign = getSignature($params, "27e1be4fdcaa83d7f61c489994ff6ed6");
Java code implementation
The java code implementation method for getting a signature is as follows:
/*** Signature generation algorithm * @ param HashMap
Params request parameter set. All parameters must be converted to the String type * @ param String secret signature key * @ return signature * @ throws IOException */public static String getSignature (HashMap
Params, String secret) throws IOException {// sort the parameters in the lexicographic ascending order of their parameter names by Map
SortedParams = new TreeMap
(Params); Set
> Entrys = sortedParams. entrySet (); // traverses the sorted dictionary and concatenates all parameters in the "key = value" format. StringBuilder basestring = new StringBuilder (); for (Entry
Param: entrys) {basestring. append (param. getKey ()). append ("= "). append (param. getValue ();} basestring. append (secret); // use MD5 to sign the signature string byte [] bytes = null; try {MessageDigest md5 = MessageDigest. getInstance ("MD5"); bytes = md5.digest (basestring. toString (). getBytes ("UTF-8");} catch (GeneralSecurityException ex) {throw new IOException (ex );} // convert the MD5 output binary result to a lowercase hexadecimal StringBuilder sign = new StringBuilder (); for (int I = 0; I <bytes. length; I ++) {String hex = Integer. toHexString (bytes [I] & 0xFF); if (hex. length () = 1) {sign. append ("0");} sign. append (hex);} return sign. toString ();}
Note:When calculating the signature, the keys and values of all parameters must be converted to the corresponding string type first, because the content transmitted in the HTTP request is of the string type, which is not noticed by many developers, the binary value of a non-string type parameter is directly passed in. As a result, the signature is inconsistent with that calculated by the server and an error occurs.
C # code implementation
The C # code implementation method for getting a signature is as follows:
////// Calculate the parameter signature //////Request parameter set. All parameters must be converted to string type.///Signature key///
Signature
Public static string getSignature (IDictionary
Parameters, string secret) {// sort the parameters in the lexicographically ascending order. IDictionary
SortedParams = new SortedDictionary
(Parameters); IEnumerator
> Iterator = sortedParams. getEnumerator (); // traverses the sorted dictionary and concatenates all parameters in the "key = value" format. StringBuilder basestring = new StringBuilder (); while (iterator. moveNext () {string key = iterator. current. key; string value = iterator. current. value; if (! String. IsNullOrEmpty (key )&&! String. isNullOrEmpty (value) {basestring. append (key ). append ("= "). append (value) ;}} basestring. append (secret); // use MD5 to sign the signature string MD5 = MD5.Create (); byte [] bytes = md5.ComputeHash (Encoding. UTF8.GetBytes (basestring. toString (); // convert the binary result output by MD5 to a lower-case hexadecimal StringBuilder result = new StringBuilder (); for (int I = 0; I <bytes. length; I ++) {string hex = bytes [I]. toString ("x"); if (hex. length = 1) {result. append ("0");} result. append (hex);} return result. toString ();}
After the Server accepts the request, it also signs the parameter. If the signature is the same, the data is not modified or lost.
Note:When calculating the signature, the keys and values of all parameters must be converted to the corresponding string type first, because the content transmitted in the HTTP request is of the string type, which is not noticed by many developers, the binary value of a non-string type parameter is directly passed in. As a result, the signature is inconsistent with that calculated by the server and an error occurs.