Geeks With Blogs
.Nettuce Code Salad
    public class OAuthSignatureGenerator
    {
        private const string OAuthConsumerKey = "oauth_consumer_key";
        private const string OAuthNonce = "oauth_nonce";
        private const string OAuthSignatureMethod = "oauth_signature_method";
        private const string OAuthTimestamp = "oauth_timestamp";
        private const string OAuthToken = "oauth_token";
        private const string OAuthVersion = "oauth_version";
 
        public enum SignatureMethod
        {
            Plaintext,
            HmacSha1
        }
 
        public static string GenerateSignature(Uri uristring httpMethodstring consumerKeystring consumerSecretstring noncestring timestampSignatureMethod signatureMethodstring token = nullstring tokenSecret = nullstring version = null)
        {
            if (signatureMethod == SignatureMethod.Plaintextreturn HttpUtility.UrlEncode(string.Format("{0}&{1}"consumerSecrettokenSecret));
            var parameters = ConvertQueryStringToListOfKvp(uri.Query);
            AddParameter(parametersOAuthConsumerKeyconsumerKey);
            AddParameter(parametersOAuthNoncenonce);
            AddParameter(parametersOAuthSignatureMethod"HMAC-SHA1");
            AddParameter(parametersOAuthTimestamptimestamp);
            if (!string.IsNullOrEmpty(token)) AddParameter(parametersOAuthTokentoken);
            if (!string.IsNullOrWhiteSpace(version)) AddParameter(parametersOAuthVersionversion);
            parameters.Sort((xy) => x.Key == y.Key ? string.Compare(x.Valuey.Value) : string.Compare(x.Keyy.Key));
 
            var normalizedUrl = string.Format("{0}://{1}{2}{3}"uri.Schemeuri.Host, (uri.Scheme == "http" && uri.Port == 80) || (uri.Scheme == "https" && uri.Port == 443) ? null : ":" + uri.Porturi.AbsolutePath);
            var normalizedRequestParameters = string.Join(nullparameters.Select(x => "&" + x.Key + "=" + x.Value)).TrimStart('&');
 
            var signatureData = string.Format("{0}&{1}&{2}"httpMethod.ToUpper(), UrlEncode(normalizedUrl), UrlEncode(normalizedRequestParameters));
 
            return ComputeHash(consumerSecrettokenSecretsignatureData);
        }
 
        private static List<KeyValuePair<stringstring>> ConvertQueryStringToListOfKvp(string queryString)
        {
            return Regex.Matches(queryString@"(\w+)=.*?(?:&|$)").Cast<Match>().Select(x => x.Value.TrimEnd('&').Split('=')).Select(x => new KeyValuePair<stringstring>(x[0], x[1])).ToList();
        }
 
        private static void AddParameter(ICollection<KeyValuePair<stringstring>> parametersstring keystring value)
        {
            parameters.Add(new KeyValuePair<stringstring>(keyvalue));
        }
 
        private static string ComputeHash(string consumerSecretstring tokenSecretstring signatureData)
        {
            var hash = new HMACSHA1 { Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}"UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? string.Empty : UrlEncode(tokenSecret))) }.ComputeHash(Encoding.ASCII.GetBytes(signatureData));
            return Convert.ToBase64String(hash);
        }
 
        private static string UrlEncode(string value)
        {
            if (string.IsNullOrWhiteSpace(value)) return string.Empty;
            const string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
            return value.Select(x => x.ToString()).Aggregate((xy) => x + (unreservedChars.Contains(y.ToString()) ? y : HttpUtility.UrlEncode(y).ToUpper()));
        }
    }
Posted on Tuesday, August 16, 2011 3:11 PM | Back to top


Comments on this post: OAuth Signature Generator

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net