Generate OAuth1 signature in C#

女生的网名这么多〃 提交于 2021-02-04 18:38:05

问题


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

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...

My code :

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();

        //...

}

And the signature generator method :

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;
}

Thank you in advance :)


回答1:


There is a type oauth_vesrion should be oauth_version




回答2:


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;
    }



回答3:


Your signature base parameters are out of order. These values are sorted on their encoded names, and if equal, based on their encoded values. So your SigBaseStringParams should look like this:

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


来源:https://stackoverflow.com/questions/35677711/generate-oauth1-signature-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!