在 C# 中生成 OAuth1 签名

编程入门 行业动态 更新时间:2024-10-26 00:24:33
本文介绍了在 C# 中生成 OAuth1 签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大问题.我在 C# 中处理 UWP Windows 10 应用程序,我想使用 OAuth 1.

I've a big problem. I work on a UWP Windows 10 application in C# and i would like to use OAuth 1.

一切都差不多,但签名是错误的.但是,我在 Microsoft GitHub 上找到了示例代码.显然,我做了一些修改...

All is almost okay BUT the signature is wrong. However, I found the sample code on the Microsoft GitHub. Obviously, I have done some modifications...

我的代码:

private async Task GoCo()
{
        String LifeInvaderUrl = "http://stage.api.lolilolz.be/v8/login";

        string timeStamp = GetTimeStamp();
        string nonce = GetNonce();
        string consumerKey = "noob-stage";
        string consumerSecret = "TOPSECRETxxXXxx";

        string SigBaseStringParams = "oauth_consumer_key=" + consumerKey;
        SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
        SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
        SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
        SigBaseStringParams += "&" + "oauth_version=1.0";

        string SigBaseString = "POST&";
        SigBaseString += Uri.EscapeDataString(LifeInvaderUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

        String Signature = GetSignature(SigBaseString, consumerSecret);

        string authorizationHeaderParams = "oauth_consumer_key="" + consumerKey + "", oauth_signature_method="HMAC-SHA1", oauth_timestamp="" + timeStamp + "", oauth_nonce="" + nonce +   "", oauth_vesrion="1.0", oauth_signature="" + Uri.EscapeDataString(Signature)+ """;

        HttpClient httpClient = new HttpClient();

        //...

}

和签名生成器方法:

string GetSignature(string sigBaseString, string consumerSecretKey)
{
        IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(consumerSecretKey + "&", BinaryStringEncoding.Utf8);
        MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
        CryptographicKey MacKey = HmacSha1Provider.CreateKey(KeyMaterial);
        IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(sigBaseString, BinaryStringEncoding.Utf8);
        IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
        string Signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

        return Signature;
}

先谢谢你:)

推荐答案

您的基本字符串参数有问题.对于 OAuth 1.0,需要对其进行排序.我已经创建了用于创建基本字符串的通用函数.你可以使用它.

Your base string parameters are out of order. For OAuth 1.0 it needs to be sorted. I have created generic function for creating base string. you can use that.

`        private static string GetSignatureBaseString(string strUrl, string TimeStamp,
            string Nonce, string strConsumer, string strOauthToken, SortedDictionary<string, string> data)
        {
            //1.Convert the HTTP Method to uppercase and set the output string equal to this value.
            string Signature_Base_String = "POST";
            Signature_Base_String = Signature_Base_String.ToUpper();

            //2.Append the ‘&’ character to the output string.
            Signature_Base_String = Signature_Base_String + "&";

            //3.Percent encode the URL and append it to the output string.
            string PercentEncodedURL = Uri.EscapeDataString(strUrl);
            Signature_Base_String = Signature_Base_String + PercentEncodedURL;

            //4.Append the ‘&’ character to the output string.
            Signature_Base_String = Signature_Base_String + "&";

            //5.append OAuth parameter string to the output string.
            var parameters = new SortedDictionary<string, string>
            {
                {"oauth_consumer_key", strConsumer},
                { "oauth_token", strOauthToken },
                {"oauth_signature_method", "HMAC-SHA1"},
                {"oauth_timestamp", TimeStamp},
                {"oauth_nonce", Nonce},
                {"oauth_version", "1.0"}
            };

            //6.append parameter string to the output string.
            foreach (KeyValuePair<string, string> elt in data)
            {
                parameters.Add(elt.Key, elt.Value);
            }

            bool first = true;
            foreach (KeyValuePair<string, string> elt in parameters)
            {
                if (first)
                {
                    Signature_Base_String = Signature_Base_String + Uri.EscapeDataString(elt.Key + "=" + elt.Value);
                    first = false;
                }
                else
                {
                    Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&" + elt.Key + "=" + elt.Value);
                }
            }

            return Signature_Base_String;
        }

`使用上面的函数,您将获得可以使用您的密钥传递给下面的函数并获得签名的基础

` Using above function you will get base which you can pass to below function with your secret key and get signature

private static string GetSha1Hash(string key, string base)
    {
        var encoding = new System.Text.ASCIIEncoding();

        byte[] keyBytes = encoding.GetBytes(key);
        byte[] messageBytes = encoding.GetBytes(base);

        string strSignature = string.Empty;

        using (HMACSHA1 SHA1 = new HMACSHA1(keyBytes))
        {
            var Hashed = SHA1.ComputeHash(messageBytes);
            strSignature = Convert.ToBase64String(Hashed);
        }

        return strSignature;
    }

这篇关于在 C# 中生成 OAuth1 签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 23:40:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/744727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!