Reprint-Common API interface Signature Verification reference

Source: Internet
Author: User
Tags openid sha1

Original address: http://www.cnblogs.com/hnsongbiao/p/5478645.html

Write well, just make a note. Thanks to the author!

Common API interface Signature verification methods in the project:

1. Assign the corresponding key and secret to the app
2. Sign signature, call the API when you need to sign the request parameters to verify, the signature method is as follows:
A. Follow the request parameter name to sort all the request parameters in alphabetical order: Keyvaluekeyvalue...keyvalue string such as: Arong=1,mrong=2,crong=3 sorted as: arong=1, crong=3, Mrong=2 then the parameter name and the parameter value are stitched together to get the argument string: arong1crong3mrong2;
B. Secret is added to the header of the parameter string and MD5 encrypted, and the encrypted string is capitalized. That is to get signed sign;

Approximate processing process

The user verifies and determines whether the key exists, and queries the corresponding secret for verification;

....

Verify the signature, according to the algorithm to sign the parameters to get signed and the parameters in the comparison of signs;

....

Socialize Data Acquisition List

Such as

App call:http://api.test.com/getproducts?key=app_key&sign=bcc7c71cf93f9cdbdb88671b701d8a35& parameter 1=value1 & Parameters 2=value2 ....
Note: Secret is used only for encryption purposes and is not used in request parameters in order to ensure data security.

The uniqueness of the request: to prevent others from reusing the request parameter problem, we need to ensure that the request is unique, that the corresponding request can only be used once, so that even if someone else takes the complete link to the request is not valid.
Uniqueness implementation: In the request parameter as above, we add timestamp: Timestamp (YYYYMMDDHHMMSS), similarly, timestamp as one of the request parameters, also added to the sign algorithm for encryption.

Here are 2 ways to verify your signature: Timestamp note the processing of the addition and validation

1. OpenID Signature and verification

        /// <summary>         ///Generate Code/// </summary>         /// <param name= "OpenID" >OpenID</param>         /// <param name= "key" >Who to jump to who rules the key</param>         /// <returns></returns>          Public Static stringMakecode (stringOpenidstringkey) {DateTime time=DateTime.Now; stringdata = time. ToString ("DD") +"_"+ OpenID +"_"+ Time. ToString ("yyyy") +"_"+ key +"_"+ Time. ToString ("MM"); MD5 MD5=NewMD5CryptoServiceProvider (); byte[] result =Encoding.Default.GetBytes (data); byte[] Output =Md5.computehash (Result); Data= bitconverter.tostring (Output). Replace ("-","").             ToLower (); SHA1CryptoServiceProvider SHA1=NewSHA1CryptoServiceProvider (); byte[] bytes = Sha1.computehash (Encoding.ASCII.GetBytes (data));//"596d42faf5710b35c7ea0f0a9600ee31" f69d39e1ca07fc23c1ce62f549e9d5b9780//turn 16 binary to clear the front 0StringBuilder StrB =NewStringBuilder ();  for(inti =0; I < bytes. Length; i++)             {                 stringstrX2 = Bytes[i]. ToString ("X2"); if(Strx2.substring (0,1) =="0") {strX2= Strx2.substring (1,1);             } strb.append (strX2); }             returnstrb.tostring (); }         /// <summary>         ///Code Validation/// </summary>         /// <param name= "OpenID" >OpenID</param>         /// <param name= "code" >data to be validated</param>         /// <param name= "key" >your own system-defined key</param>         /// <returns></returns>          Public Static BOOLValidatecode (stringOpenidstringCodestringkey) {             stringSigneddata =Makecode (OpenID, key); returncode.         Equals (Signeddata, stringcomparison.ordinalignorecase); }

2. Request parameter signature and verification

        /// <summary>         ///to sign the request/// </summary>         /// <param name= "Parameters" >request parameters for all character types</param>         /// <param name= "Secret" >Signature Key</param>         /// <param name= "QHS" >whether the signature is encrypted before and after</param>         /// <returns></returns>          Public stringSignrequest (idictionary<string,string> Parameters,stringSecretBOOLQHS) {             //The first step: Sort the dictionary alphabetically by keyidictionary<string,string> sortedparams =Newsorteddictionary<string,string>(parameters); IEnumerator<KeyValuePair<string,string>> dem =Sortedparams.getenumerator (); //Step Two: string all parameter names and values togetherStringBuilder query =NewStringBuilder (Secret);  while(Dem. MoveNext ()) {stringKey =dem.                 Current.key; stringValue =dem.                 Current.value; if(!string. Isnullorwhitespace (Key))//!string. Isnullorwhitespace (value) null value also added to the calculation??  {query. Append (Key).                 Append (value); }             }             if(QHS) {query.             Append (secret); }             //Part III: Using MD5 operationsMD5 MD5 =MD5.             Create (); byte[] bytes =Md5.computehash (Encoding.UTF8.GetBytes (query.             ToString ())); //Fourth: Hex to capitalize binaryStringBuilder result =NewStringBuilder ();  for(inti =0; I < bytes. Length; i++) {result. Append (Bytes[i]. ToString ("X2")); }             returnresult.         ToString (); }          /// <summary>         ///Verifying Signatures/// </summary>         /// <returns></returns>          Public BOOLValidatesign (stringsecret) {             stringMETHOD =HttpContext.Current.Request.HttpMethod; System.Collections.Specialized.NameValueCollection form=HttpContext.Current.Request.QueryString; Switch(method) { Case "POST": Form=HttpContext.Current.Request.Form;  Break;  Case "GET": Form=HttpContext.Current.Request.QueryString;  Break; default:                     return false; } IDictionary<string,string> Parameters =Newdictionary<string,string>(); stringSign =string.             Empty;  for(inti =0; I < form. Count; i++)             {                 stringKey =form.                 Keys[i]; if(string. Equals (Key," Sign", StringComparison.OrdinalIgnoreCase)) { Sign= form[" Sign"]; Continue; } parameters.             ADD (Key,form[key]); }             return string. Equals (signrequest (Parameters, Secret,false), sign,stringcomparison.ordinalignorecase); }

Reprint-Common API interface Signature Verification reference

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.