How token is used in the API

Source: Internet
Author: User
Tags md5 encryption

Recently found that the company interface is a simple method of verification is simple user name password verification. The owner of the customer said to modify, so think of the way to verify the password to write this demo for everyone to learn the reference;

Interface: WebService

Mode: Token dynamic encryption signature;

WebService Header Parameter Description:

Signature: Cryptographic signature, String type;

Timestamp: Current timestamp, datetime type (note that client time and service-side difference cannot be greater than 7 seconds, can be modified)

Nonce: Random number, String type;

Parameter handling:

    1. The client uses the string of token+ timestamp+ nonce to sort the dictionary;
    2. The client encrypts the sorted string MD5;
    3. The encrypted string is passed as the signature parameter to the server;

Service-Side code:

<summary>

WebService interface SoapHeader Class

</summary>

public class APISoapHeader:System.Web.Services.Protocols.SoapHeader

{

<summary>

Encrypt signature

</summary>

public string Signature {get; set;}

<summary>

Time stamp

</summary>

Public DateTime timestamp{get; set;}

<summary>

Random number

</summary>

public string Nonce {get; set;}

}

<summary>

Summary description of WebService1

</summary>

[WebService (Namespace = "http://tempuri.org/")]

[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]

[System.ComponentModel.ToolboxItem (False)]

To allow this Web service to be called from a script using ASP. NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]

public class WebService1:System.Web.Services.WebService

{

Public Apisoapheader Header {get; set;}

[System.Web.Services.Protocols.SoapHeader ("header")]

[WebMethod]

public string HelloWorld (String msg)

{

if (header = null && tokenhelper.tokenverify (header.signature, Header.timestamp, header.nonce))

{

Return "Hello World:" + msg;

}

Else

{

return "NO";

}

}

}

Verification Code:

Public abstract class Tokenhelper

{

<summary>

Verifying cryptographic signatures

</summary>

<param name= "Header" ></param>

<returns></returns>

public static bool Tokenverify (string signature,datetime Timestamp, string nonce)

{

BOOL isOK = false;

if (!string. IsNullOrEmpty (signature)

&&!string. IsNullOrEmpty (nonce))

{

TimeSpan ts = DateTime.Now.Subtract (timestamp). Duration ();

if (TS. Seconds < 7)//If the request end timestamp and the system time difference is less than 7 seconds, continue to verify

{

if (signature. Equals (Tokenhelper.getsignature (timestamp, nonce)))

{

return true;

}

}

}

return isOK;

}

<summary>

Get the cryptographic signature

</summary>

<param name= "Timestamp" ></param>

<param name= "Nonce" ></param>

<returns></returns>

public static string Getsignature (DateTime timestamp, string nonce)

{

String token = system.configuration.configurationmanager.appsettings["ApiToken"];

String str = string. Format ("{0}{1}{2}", token, timestamp. ToString (), nonce);

list<char> str2 = str. Tolist<char> ();

Str2. Sort ();

String str3 = "";

foreach (var item in str2)

{

STR3 = string. Format ("{0}{1}", STR3, item. ToString ());

}

Return Tokenhelper.md5encrypt (STR3);

}

<summary>

MD5 encryption

</summary>

<param name= "StrText" ></param>

<returns></returns>

public static string Md5encrypt (String strText)

{

String cryptstr = "";

MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider ();

byte[] bytes = Encoding.UTF8.GetBytes (StrText);

byte[] cryptbytes = Md5.computehash (bytes);

for (int i = 0; i < cryptbytes.length; i++)

{

Cryptstr + = Cryptbytes[i]. ToString ("X2");

}

return cryptstr;

}

}

Test code:

Class Program

{

static void Main (string[] args)

{

String msg = Console.ReadLine ();

Servicereference1.webservice1soapclient client = new Servicereference1.webservice1soapclient ();

Servicereference1.apisoapheader Header = new Servicereference1.apisoapheader ();

Random random = new random ();

Header.timestamp = DateTime.Now;

Header.nonce = random. Next (0, 100). ToString ();

Header.signature = Tokenhelper.getsignature (Header.timestamp, header.nonce);

Thread.Sleep (7000);//If greater than 7 seconds fails;

msg = client. HelloWorld (header, msg);

Console.WriteLine (msg);

Console.readkey ();

}

}

The advantage of this method is that the transmission password is changed at any time, and even if the third party intercepted the password, to decrypt according to two dynamic values is quite difficult, and the intercepted password can only be used for 7 seconds, 7 seconds after the automatic failure;

How token is used in the API

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.