HMAC-SHA1 algorithm signature and Authorization header authentication

Source: Internet
Author: User
Tags base64 hmac sha1

Use PHP for HMAC-SHA1 signing and Authorization header authentication Deom

$app _id= ' id ';$host= "Test.abc.com";$port= "80";$app _key= "Key";$app _timestamp= Time();$app _nonce= "8FINTYTUSKBSZGFL". Time().Rand(10,1000);$uri= "/account/ass/verify.do";//Build String$arr=Array($app _timestamp,$app _nonce, "POST",$uri,$host,$port);$text=Join("\ n",$arr) . "\ n";Var_dump($text);$sig= Get_signature ($text,$app _key);Var_dump($sig);$headers=Array();$headers[] = "Authorization:mac id=\"$app _id\ ", ts=\"$app _timestamp\ ", nonce=\"$app _nonce\ ", mac=\"$sig\"";$headers[]= "Content-type:application/json";$data= ' {' h ': ' 2d4d9be245fc4172989bc5fad7ec8784 ', ' n ': ' 97c5237b ', ' t ': ' 1428462620 ', ' V ': ' 8F2ACF569FCBFDA9081248486240170B325AFF6D "}";$result= Curlpost (' http://t-id.gionee.com ').$uri,$headers,$data);/** * @ Use HMAC-SHA1 algorithm to generate oauth_signature signature value * * @param $key key * @param $str Source String * * @return Signature value*/functionGet_signature ($str,$key) {    $signature= ""; if(function_exists(' Hash_hmac ')) {        $signature=Base64_encode(Hash_hmac ("SHA1",$str,$key,true)); } Else {        $blocksize= 64; $hashfunc= ' SHA1 '; if(strlen($key) >$blocksize) {            $key=Pack(' h* ',$hashfunc($key)); }        $key=Str_pad($key,$blocksize,CHR(0x00)); $ipad=str_repeat(CHR(0x36),$blocksize); $opad=str_repeat(CHR(0X5C),$blocksize); $hmac=Pack(            ' H* ',$hashfunc(                ($key^$opad) .Pack(                    ' H* ',$hashfunc(                        ($key^$ipad) .$str                    )                )            )        ); $signature=Base64_encode($hmac); }    return $signature;}functionCurlpost ($url,$headers=Array(),$data=Array()) {    $ch=Curl_init (); curl_setopt ($ch, Curlopt_url,$url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_ssl_verifypeer,false);//setting does not verify SSL, this line is required when sending HTTPS interface requestscurl_setopt ($ch, Curlopt_ssl_verifyhost,false);//setting does not verify SSL, this line is required when sending HTTPS interface requests    if(!Empty($data) {curl_setopt ($ch, Curlopt_post, 1); curl_setopt ($ch, Curlopt_postfields,$data); }    if(!Empty($headers) {curl_setopt ($ch, Curlopt_httpheader,$headers); Var_dump(' Set Header '); Var_dump($headers); }    $output= Curl_exec ($ch); Curl_close ($ch); return $output;}

Attached: Java Algorithm example:

 PackageNet.svr.cas.test.demo;Importjava.io.UnsupportedEncodingException;Importjava.security.InvalidKeyException;Importjava.security.NoSuchAlgorithmException;ImportJavax.crypto.Mac;ImportJavax.crypto.spec.SecretKeySpec;Importnet.iharder.Base64; Public classSig_demo_app {Private Static FinalString mac_name = "HmacSHA1"; Private Static FinalString UTF8 = "UTF-8"; Private Static Final byte[] BYTEARRAY =New byte[0];  Public Static voidMain (string[] args) {String host= "id.test.cn"; String Port= "443"; String App_key= "Please fill in your Appkey"; String App_timestamp= "1369732102"; String app_nonce= "8FINTYTUSKBSZGFL"; String URI= "/account/verify.do"; String Sig= Macsig (host, Port, App_key, App_timestamp, App_nonce, "POST", URI);    System.out.println (SIG); }     Public Staticstring Macsig (string host, String port, String MacKey, string timestamp, string nonce, String method, string uri) { //1. Build Mac String//2. Hmac-sha1//3. base64-encodedStringBuffer Buffer=NewStringBuffer (); Buffer.append (timestamp). Append ("\ n"); Buffer.append (nonce). Append ("\ n"); Buffer.append (Method.touppercase ()). Append ("\ n"); Buffer.append (URI). Append ("\ n"); Buffer.append (Host.tolowercase ()). Append ("\ n"); Buffer.append (Port). Append ("\ n"); Buffer.append ("\ n"); String text=buffer.tostring ();        System.out.println (text); byte[] ciphertext =NULL; Try{ciphertext=Hmacsha1encrypt (MacKey, text); } Catch(Throwable e) {return NULL; } String sigstring=base64.encodebytes (ciphertext); returnsigstring; }     Public Static byte[] Hmacsha1encrypt (String encryptkey, String encrypttext)throwsInvalidKeyException, nosuchalgorithmexception {mac Mac=mac.getinstance (mac_name); Mac.init (NewSecretkeyspec (GetBytes (Encryptkey), mac_name)); returnmac.dofinal (GetBytes (Encrypttext)); }         Public Static byte[] getBytes (String value) {returngetBytes (value, UTF8); }     Public Static byte[] getBytes (String value, String charset) {if(IsNullOrEmpty (value))returnBYTEARRAY; if(IsNullOrEmpty (CharSet)) CharSet=UTF8; Try {            returnvalue.getbytes (CharSet); } Catch(unsupportedencodingexception e) {returnBYTEARRAY; }    }         Public Static BooleanIsNullOrEmpty (String s) {if(s = =NULL|| S.isempty () | |S.trim (). IsEmpty ())return true; return false; }}

HMAC-SHA1 algorithm signature and Authorization header authentication

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.