URI parameter Signature Algorithm "reprint"

Source: Internet
Author: User
Tags http post

Introduction

When the application sends an open API call request based on an HTTP POST or HTTP GET request, the Baidu rest server uses a parameter signing mechanism to ensure secure communication between the application and the Baidu rest server to prevent malicious attacks such as secret key theft and data tampering. Before invoking the Baidu Open API, the application needs to compute a MD5 signature for all of its request parameters, appended to the request parameters, with the parameter name "sign". The Baidu rest server will recalculate the signature when it receives the request and determine whether its value is consistent with the value of the sign parameter passed by the app to determine whether the current open API call request was forged or tampered with by a third party.

Before calling the open API, the application needs to obtain the authorization of the user or platform through the Baidu OAuth2.0 service, and after obtaining the authorization, it will get the following 3 important parameters:

    • Access_token: The Access authorization code required to invoke the open API based on HTTPS;
    • Session_key: The Access authorization code required to invoke the Open API based on HTTP;
    • Session_secret: The signature key used to calculate parameter signatures when invoking the open API based on HTTP.

Where session_secret This parameter is the signature key required to do the parameter signature. This is slightly different from the Facebook, Renren, and other platforms, which typically have 2 signature keys for the two platform signatures:

    • If the open API is called through the application server, the application key (i.e. API key) that is obtained when registering the application is the parameter signature key;
    • If the open API is called through the client language, such as JavaScript, ActionScript, the session secret that the app obtains to the user's authorization is the parameter signing key. Of course, you can also use session secret as the signing key when invoking the open API through the server.
Signature Algorithm

Assuming that the request parameters that participate in the parameter signature calculation are "K1", "K2", "K3", respectively, their values are "V1", "V2", and "V3", then the parameter signature is computed as follows:

    • The request parameter is formatted as "key=value" format, i.e. "K1=v1", "K2=v2", "K3=v3";
    • The formatted parameter key value pairs are arranged in ascending order of dictionary order, and then join together, that is, "k1=v1k2=v2k3=v3";
    • At the end of the concatenation of the string appended to the application through the Baidu OAuth2.0 agreement to obtain access token obtained by the Session_secret parameter value;
    • The MD5 value of the above string is the value of the signature.

Note: Do not include the sign (signature) parameter in the request parameter when the signature is computed, because it is not known at the time of the signing parameter and remains to be computed .

In addition, the parameter does not need to be urlencode processed ("application/x-www-form-urlencoded" code) when the signature is computed, but the UrlEncode processing is required when sending the request, which is the most error-prone place for many developers.

Signature Process Example

Assuming that an application needs to obtain basic information about a user with a UID of 67411167, the Session_key and Session_secret parameter values obtained in the previous process of obtaining access tokens through the Baidu OAuth2.0 service are:

    • Session_key: "9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a="
    • Session_secret: "27e1be4fdcaa83d7f61c489994ff6ed6"

The system time when invoking the Open API (PHP can get the current system time by date (' y-m-d h:i:s ')) is "2011-06-21 17:18:09" and I want the rest server to return the call result in JSON format. The set of request parameters that are equivalent to participating in the parameter signature calculation is:

[    "Session_key" = "9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a=",    "timestamp "= =" 2011-06-21 17:18:09 ",    " format "and" JSON ",    " UID "+ 67411167]

The exact process for calculating the signature is as follows:

    • The request parameter is formatted as a "key=value" format, and the formatted request parameter collection is:
[    "session_key=9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a=",    "timestamp= 2011-06-21 17:18:09 ",    " Format=json ",    " uid=67411167 "]
    • The formatted parameter key pairs are sorted in ascending order of the dictionary order, resulting in the following set of parameters:
[    "Format=json",    "session_key=9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a=",    "Timestamp=2011-06-21 17:18:09",    "uid=67411167"]
    • The previously ordered set of parameters is stitched together to get the following string:
format=jsonsession_key=9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a=timestamp= 2011-06-21 17:18:09uid=67411167
    • Append the string at the end of the concatenation of the value of the Session_secret parameter obtained when using the Baidu OAuth2.0 protocol to obtain access token, get the following string:
format=jsonsession_key=9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a=timestamp= 2011-06-21 17:18:09uid=6741116727e1be4fdcaa83d7f61c489994ff6ed6
    • For the previously obtained string to MD5 signature, the resulting d24dd357a95a2579c410b3a92495f009 is called the API to call the value of the sign parameter.

Next, you can request the rest server of the Baidu Open API through the HTTP POST method or the HTTP GET method, and make an interface call, such as:

get/rest/2.0/passport/users/getinfo?session_key= 9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a%3d&timestamp=2011-06-21+17%3a18%3a09 &format=json&uid=67411167&sign=d24dd357a95a2579c410b3a92495f009 HTTP/1.1Host: 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.1host:openapi.baidu.comuser-agent:client of Baidu Open platformaccept: */*accept-encoding:gzip,deflateaccept-charset:utf-8content-length:179connection:close Session_key=9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a%3d&timestamp=2011-06-21+17 %3a18%3a09&format=json&uid=67411167&sign=d24dd357a95a2579c410b3a92495f009

Signature Algorithm Implementation codePHP Code Implementation

The PHP code that gets the signature is implemented as follows:

/**  * Signature generation algorithm  * @param  An associative array of the collection of request parameters for the array $params API call, does not contain the sign parameter  * @param  string $secret The signed key is the session returned when you get access token secret  * @return string returns the parameter signature value *  /function getsignature ($params, $secret) { c11/> $str = ";  String    to be signed//the parameter is sorted in ascending order of the dictionary order of its parameter name    ksort ($params);    Iterates through each key/value of the sorted parameter array to    foreach ($params as $k + $v) {        //for Key/value to generate a key=value-formatted string, and stitching it $str after the string to be signed        . = "$k = $v";    }    The signature key is stitched to the last face of the signature string    $str. = $secret;    Generate a MD5 signature for the signature string using the MD5 algorithm, which is the sign parameter value we want to append    return MD5 ($STR);}

Invocation Example:

$uid = 67411167; $params = Array (    "Session_key" and "=" 9xnnxe66zolsassjskd5gry9bin61iuei8ipjmjbwvu07rxp0j3c4gnhzr3gkhmha1a= ",    " timestamp "and" 2011-06-21 17:18:09 ",    " format "=" json ",    " uid "= = $uid,); $sign = Getsignature ($params," 27e1be4fdcaa83d7f61c489994ff6ed6 " );
Java Code Implementation

The Java code that gets the signature is implemented as follows:

/** * Signature Generation algorithm * @param hashmap<string,string> params request parameter set, all parameters must have been converted to String type * @param string secret signing key * @return Signature * @throws ioexception */public static string Getsignature (hashmap<string,string> params, String secret) throws Ioexc    eption{//The parameter is sorted in ascending order of the dictionary order of its parameter name map<string, string> sortedparams = new treemap<string, string> (params);     set<entry<string, string>> Entrys = Sortedparams.entryset ();    Iterate through the sorted dictionary and stitch all parameters together in "Key=value" format StringBuilder basestring = new StringBuilder (); For (entry<string, string> Param:entrys) {basestring.append (Param.getkey ()). Append ("="). Append (Param.getva    Lue ());     } basestring.append (Secret);    Use MD5 to treat the signature string kissingly 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 binary result of MD5 output to 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: the key and value of all parameters must first be converted to the corresponding string type when the signature is computed, because the content passed in the HTTP request is a string type, and many developers simply pass in the binary value of the non-string type parameter because they do not notice it. The result is an inconsistency between the signature and the server-side calculation and error.

C # code implementation

The C # code that gets the signature is implemented as follows:

<summary>///Calculate parameter signature///</summary>///<param name= "params" > Request parameter set, all parameters must have been converted to string type </param> <param name= "secret" > Signing key </param>///<returns> signature </returns>public static string Getsignature (idictionary<string, string> parameters, String secret) {//The parameter is sorted first with the dictionary order of its parameter name Idictionary<str    ing, string> sortedparams = new sorteddictionary<string, string> (parameters);     Ienumerator<keyvaluepair<string, string>> iterator= sortedparams.getenumerator ();    Iterate through the sorted dictionary and stitch all parameters together in "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 treat the signature string kissingly MD5 MD5 = MD5.    Create (); byte[] bytes = Md5.computehash (Encoding.UTF8.GetBytes (basestring.     ToString ()));    Converts the binary result of the MD5 output to lowercase 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 ();}

URI parameter Signature Algorithm "reprint"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.