.net 开发有大神指点 ?
点****媒 · 点****媒 发布于2015-10-19 10:49 浏览:3190 回复:12

用.net照着HTTP RESULT API  post方式 访问api  老是返回401,有没有做过了求指点呀。 。 

点赞  ( 0 )
收藏
评论(12)
共12条回复 最后由忽****我回复于2016-01-08 23:41
#2高****师回复于2015-10-19 15:25:36

        date_default_timezone_set('UTC');

        $AK = "yourAK";

        $timestamp = date("Y-m-d")."T".date("H:i:s")."Z";

        $expirationPeriodInSeconds = "3600";

        $SK="yourSK";

        $authStringPrefix = "bce-auth-v1"."/".$AK."/".$timestamp."/".$expirationPeriodInSeconds;


        $SigningKey=hash_hmac('SHA256',$authStringPrefix,$SK);


        $CanonicalHeaders1 = "host;"."x-bce-date";

        $CanonicalHeaders2 = "host:sms.bj.baidubce.com\n"."x-bce-date:".urlencode($timestamp);//

print "CanonicalHeaders2:".$CanonicalHeaders2."\n";

        $CanonicalString = "";

        $CanonicalURI = "/v1/message";

        $CanonicalRequest = "POST\n".$CanonicalURI."\n".$CanonicalString."\n".$CanonicalHeaders2;       //第二步

print "CanonicalRequest:".$CanonicalRequest."\n";

        $Signature = hash_hmac('SHA256',$CanonicalRequest,$SigningKey);

print "Signature:".$Signature."\n";

        $Authorization = "bce-auth-v1/{$AK}/".$timestamp."/{$expirationPeriodInSeconds}/{$CanonicalHeaders1}/{$Signature

}";

print "Authorization:".$Authorization."\n";



0
#3高****师回复于2015-10-19 15:27:19

给你个PHP的参考一下,有几个需要重点关注:1.UTC时间;2.AK、SK不能错;3.CanonicalString,即使为空也要写;

1
#4点****媒回复于2015-10-19 19:45:43
#3 高****师回复
给你个PHP的参考一下,有几个需要重点关注:1.UTC时间;2.AK、SK不能错;3.CanonicalString,即使为空也要写;

 x-bce-content-sha256  这个是怎么算出来的?

#5点****媒回复于2015-10-19 19:50:28
#3 高****师回复
给你个PHP的参考一下,有几个需要重点关注:1.UTC时间;2.AK、SK不能错;3.CanonicalString,即使为空也要写;

我也是这样做的呀。 x-bce-content-sha256  这个签名是怎么算的呢?,

0
#6高****师回复于2015-10-19 22:56:48
#5 点****媒回复
我也是这样做的呀。 x-bce-content-sha256 这个签名是怎么算的呢?,[图片]

正好在这个link中找到了类似的,可以参考一下;http://codego.net/41595/

如果link中的代码可行,那么对应的应该是这样的:

var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(signingKey));

hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest));

我不会.Net,撸主可以测试一下,如果可行,可以将这部分签名代码分享给大家。

1
#7点****媒回复于2015-10-20 08:58:40
#6 高****师回复
正好在这个link中找到了类似的,可以参考一下;http://codego.net/41595/ 如果link中的代码可行,那么对应的应该是这样的: var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(signingKey)); hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest)); 我不会.Net,撸主可以测试一下,如果可行,可以将这部分签名代码分享给大家。[图片]

这个在我写的MyHMACHash256方法是可以得到的, 我所说的是公共请求不是有个 x-bce-content-sha256 请求头吗?我没明白,这个请求头是怎么算的签名?不是很明白呢?

0
#8高****师回复于2015-10-20 15:38:39
#7 点****媒回复
这个在我写的MyHMACHash256方法是可以得到的, 我所说的是公共请求不是有个 x-bce-content-sha256 请求头吗?我没明白,这个请求头是怎么算的签名?不是很明白呢? [图片]

$head =  array("Content-Type:application/json","Authorization:{$Authorization}","x-bce-date:{$timestamp}","x-bce

-content-sha256:{$SigningKey}");

应该是前面经过hash_hmac处理后得到的SigningKey;

0
#9中****网回复于2015-10-22 16:48:50

public string SHA256Encrypt(string strIn)
        {
            byte[] Value;
            UnicodeEncoding Code = new UnicodeEncoding();
            byte[] Message = Code.GetBytes(strIn);
            SHA256Managed shaMgd = new SHA256Managed();
            Value = shaMgd.ComputeHash(Message);
            strIn = "";
            foreach (byte o in Value)
            {
                strIn += o.ToString("x2");
            }
            shaMgd.Dispose();
            return strIn;
        }

试试是用这个签名吗?

0
#10h****a回复于2015-12-15 14:54:20

public class BaiduSmsService : PowerMeasurement.WebApi.Services.SMS.ISmsService

    {

        string datetime = "";


        private string GetAuthorizationCode()

        {

            var accessKeyId = ConfigurationManager.AppSettings.Get("BaiduSMSAccessKeyId");

            var secreteKey = ConfigurationManager.AppSettings.Get("BaiduSMSSecreteKey");

            var template = "bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}/{signedHeaders}/{signature}";

            var timestamp = datetime;

            var expirationPeriodInSeconds = "3600";

            var signedHeaders = "host;x-bce-date";

            var signature = GetSignature();

            return template.Replace("{accessKeyId}", accessKeyId)

                .Replace("{accessKeyId}", accessKeyId)

                .Replace("{timestamp}", timestamp)

                .Replace("{expirationPeriodInSeconds}", expirationPeriodInSeconds)

                .Replace("{signedHeaders}", signedHeaders)

                .Replace("{signature}", signature);

        }


        private string GetSignature()

        {

            var signingKey = GetSigningKey();

            var canonical = GetCanonicalRequest();

            return GetHMACSHA256Code(signingKey, canonical);

        }


        private string GetSigningKey()

        {

            var accessKeyId = ConfigurationManager.AppSettings.Get("BaiduSMSAccessKeyId");

            var secreteKey = ConfigurationManager.AppSettings.Get("BaiduSMSSecreteKey");

            var expirationPeriodInSeconds = "3600";

            string authStringPrefix = "bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}";

            authStringPrefix = authStringPrefix.Replace("{accessKeyId}", accessKeyId)

                .Replace("{timestamp}", datetime)

                .Replace("{expirationPeriodInSeconds}", expirationPeriodInSeconds);

            var signingKey = GetHMACSHA256Code(secreteKey, authStringPrefix);

            return signingKey;

        }


        private string GetCanonicalRequest()

        {

            var method = "POST";

            var canonicalURI = "/v1/message";

            var canonicalQueryString = "";

            var host = ConfigurationManager.AppSettings.Get("BaiduSMSHost");

            var canonicalHeaders = HttpUtility.UrlEncode("host") + ":" + HttpUtility.UrlEncode(host);

            canonicalHeaders += "\n" + HttpUtility.UrlEncode("x-bce-date") + ":" + HttpUtility.UrlEncode(datetime).ToUpper();


            var canonical = method + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalHeaders;

            return canonical;

        }


        private string GetHMACSHA256Code(string key, string strContent)

        {

            var hash = new HMACSHA256(Encoding.UTF8.GetBytes(key)).ComputeHash(Encoding.UTF8.GetBytes(strContent));

            var signingKey = "";

            for (var i = 0; i < hash.Length; i++)

            {

                signingKey += hash[i].ToString("x2");

            }

            return signingKey;

        }



        public bool SendText(string to, string content)

        {

            if (to.StartsWith("86"))

            {

                to = to.Substring(2, to.Length - 2);

            }

            var host = ConfigurationManager.AppSettings.Get("BaiduSMSHost");


            var BaiduSMSTemplateId = ConfigurationManager.AppSettings.Get("BaiduSMSTemplateId");

            var smsUrl = "http://" + host + "/v1/message";

            datetime = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ssZ");

            var requestContent = new

            {

                templateId = BaiduSMSTemplateId,

                receiver = new string[] { to },

                contentVar = new

                {

                    code = content

                }

            };

            var strContent = JsonConvert.SerializeObject(requestContent);

            var btyeContent = Encoding.UTF8.GetBytes(strContent);


            var request = WebRequest.CreateHttp(smsUrl);

            request.ProtocolVersion = HttpVersion.Version11;

            request.Method = "POST";

            request.ContentType = "application/json";

            request.Headers.Add("Authorization", GetAuthorizationCode());

            request.Headers.Add("x-bce-date", datetime);

            request.Headers.Add("x-bce-content-sha256", GetSigningKey());


            using (Stream stream = request.GetRequestStream())

            {

                stream.Write(btyeContent, 0, btyeContent.Length);

            }

            HttpWebResponse res;

            try

            {

                res = (HttpWebResponse)request.GetResponse();

                var output = res.GetResponseStream();

                byte[] temp = new byte[res.ContentLength];

                output.Read(temp, 0, temp.Length);

                var txt = Encoding.UTF8.GetString(temp);


                

                Console.Write(txt);

            }

            catch (WebException ex)

            {

                res = (HttpWebResponse)ex.Response;

            }

            return true;

        }


#11h****a回复于2015-12-15 14:55:18

public class BaiduSmsService

    {

        string datetime = "";


        private string GetAuthorizationCode()

        {

            var accessKeyId = ConfigurationManager.AppSettings.Get("BaiduSMSAccessKeyId");

            var secreteKey = ConfigurationManager.AppSettings.Get("BaiduSMSSecreteKey");

            var template = "bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}/{signedHeaders}/{signature}";

            var timestamp = datetime;

            var expirationPeriodInSeconds = "3600";

            var signedHeaders = "host;x-bce-date";

            var signature = GetSignature();

            return template.Replace("{accessKeyId}", accessKeyId)

                .Replace("{accessKeyId}", accessKeyId)

                .Replace("{timestamp}", timestamp)

                .Replace("{expirationPeriodInSeconds}", expirationPeriodInSeconds)

                .Replace("{signedHeaders}", signedHeaders)

                .Replace("{signature}", signature);

        }


        private string GetSignature()

        {

            var signingKey = GetSigningKey();

            var canonical = GetCanonicalRequest();

            return GetHMACSHA256Code(signingKey, canonical);

        }


        private string GetSigningKey()

        {

            var accessKeyId = ConfigurationManager.AppSettings.Get("BaiduSMSAccessKeyId");

            var secreteKey = ConfigurationManager.AppSettings.Get("BaiduSMSSecreteKey");

            var expirationPeriodInSeconds = "3600";

            string authStringPrefix = "bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}";

            authStringPrefix = authStringPrefix.Replace("{accessKeyId}", accessKeyId)

                .Replace("{timestamp}", datetime)

                .Replace("{expirationPeriodInSeconds}", expirationPeriodInSeconds);

            var signingKey = GetHMACSHA256Code(secreteKey, authStringPrefix);

            return signingKey;

        }


        private string GetCanonicalRequest()

        {

            var method = "POST";

            var canonicalURI = "/v1/message";

            var canonicalQueryString = "";

            var host = ConfigurationManager.AppSettings.Get("BaiduSMSHost");

            var canonicalHeaders = HttpUtility.UrlEncode("host") + ":" + HttpUtility.UrlEncode(host);

            canonicalHeaders += "\n" + HttpUtility.UrlEncode("x-bce-date") + ":" + HttpUtility.UrlEncode(datetime).ToUpper();


            var canonical = method + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalHeaders;

            return canonical;

        }


        private string GetHMACSHA256Code(string key, string strContent)

        {

            var hash = new HMACSHA256(Encoding.UTF8.GetBytes(key)).ComputeHash(Encoding.UTF8.GetBytes(strContent));

            var signingKey = "";

            for (var i = 0; i < hash.Length; i++)

            {

                signingKey += hash[i].ToString("x2");

            }

            return signingKey;

        }



        public bool SendText(string to, string content)

        {

            if (to.StartsWith("86"))

            {

                to = to.Substring(2, to.Length - 2);

            }

            var host = ConfigurationManager.AppSettings.Get("BaiduSMSHost");


            var BaiduSMSTemplateId = ConfigurationManager.AppSettings.Get("BaiduSMSTemplateId");

            var smsUrl = "http://" + host + "/v1/message";

            datetime = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ssZ");

            var requestContent = new

            {

                templateId = BaiduSMSTemplateId,

                receiver = new string[] { to },

                contentVar = new

                {

                    code = content

                }

            };

            var strContent = JsonConvert.SerializeObject(requestContent);

            var btyeContent = Encoding.UTF8.GetBytes(strContent);


            var request = WebRequest.CreateHttp(smsUrl);

            request.ProtocolVersion = HttpVersion.Version11;

            request.Method = "POST";

            request.ContentType = "application/json";

            request.Headers.Add("Authorization", GetAuthorizationCode());

            request.Headers.Add("x-bce-date", datetime);

            request.Headers.Add("x-bce-content-sha256", GetSigningKey());


            using (Stream stream = request.GetRequestStream())

            {

                stream.Write(btyeContent, 0, btyeContent.Length);

            }

            HttpWebResponse res;

            try

            {

                res = (HttpWebResponse)request.GetResponse();

                var output = res.GetResponseStream();

                byte[] temp = new byte[res.ContentLength];

                output.Read(temp, 0, temp.Length);

                var txt = Encoding.UTF8.GetString(temp);


                

                Console.Write(txt);

            }

            catch (WebException ex)

            {

                res = (HttpWebResponse)ex.Response;

            }

            return true;

        }


0
TOP