· 7 years ago · Apr 18, 2018, 04:42 PM
1using System;
2using System.Security.Cryptography;
3using System.Collections.Generic;
4using System.Text;
5using System.Web;
6
7namespace OAuth {
8 public class OAuthBase {
9
10 /// <summary>
11 /// Provides a predefined set of algorithms that are supported officially by the protocol
12 /// </summary>
13 public enum SignatureTypes {
14 HMACSHA1,
15 PLAINTEXT,
16 RSASHA1
17 }
18
19 /// <summary>
20 /// Provides an internal structure to sort the query parameter
21 /// </summary>
22 protected class QueryParameter {
23 private string name = null;
24 private string value = null;
25
26 public QueryParameter(string name, string value) {
27 this.name = name;
28 this.value = value;
29 }
30
31 public string Name {
32 get { return name; }
33 }
34
35 public string Value {
36 get { return value; }
37 }
38 }
39
40 /// <summary>
41 /// Comparer class used to perform the sorting of the query parameters
42 /// </summary>
43 protected class QueryParameterComparer : IComparer<QueryParameter> {
44
45 #region IComparer<QueryParameter> Members
46
47 public int Compare(QueryParameter x, QueryParameter y) {
48 if (x.Name == y.Name) {
49 return string.Compare(x.Value, y.Value);
50 } else {
51 return string.Compare(x.Name, y.Name);
52 }
53 }
54
55 #endregion
56 }
57
58 protected const string OAuthVersion = "1.0";
59 protected const string OAuthParameterPrefix = "oauth_";
60
61 //
62 // List of know and used oauth parameters' names
63 //
64 protected const string OAuthConsumerKeyKey = "oauth_consumer_key";
65 protected const string OAuthCallbackKey = "oauth_callback";
66 protected const string OAuthVersionKey = "oauth_version";
67 protected const string OAuthSignatureMethodKey = "oauth_signature_method";
68 protected const string OAuthSignatureKey = "oauth_signature";
69 protected const string OAuthTimestampKey = "oauth_timestamp";
70 protected const string OAuthNonceKey = "oauth_nonce";
71 protected const string OAuthTokenKey = "oauth_token";
72 protected const string OAuthTokenSecretKey = "oauth_token_secret";
73
74 protected const string HMACSHA1SignatureType = "HMAC-SHA1";
75 protected const string PlainTextSignatureType = "PLAINTEXT";
76 protected const string RSASHA1SignatureType = "RSA-SHA1";
77
78 protected Random random = new Random();
79
80 protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
81
82 /// <summary>
83 /// Helper function to compute a hash value
84 /// </summary>
85 /// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
86 /// <param name="data">The data to hash</param>
87 /// <returns>a Base64 string of the hash value</returns>
88 private string ComputeHash(HashAlgorithm hashAlgorithm, string data) {
89 if (hashAlgorithm == null) {
90 throw new ArgumentNullException("hashAlgorithm");
91 }
92
93 if (string.IsNullOrEmpty(data)) {
94 throw new ArgumentNullException("data");
95 }
96
97 byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
98 byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
99
100 return Convert.ToBase64String(hashBytes);
101 }
102
103 /// <summary>
104 /// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
105 /// </summary>
106 /// <param name="parameters">The query string part of the Url</param>
107 /// <returns>A list of QueryParameter each containing the parameter name and value</returns>
108 private List<QueryParameter> GetQueryParameters(string parameters) {
109 if (parameters.StartsWith("?")) {
110 parameters = parameters.Remove(0, 1);
111 }
112
113 List<QueryParameter> result = new List<QueryParameter>();
114
115 if (!string.IsNullOrEmpty(parameters)) {
116 string[] p = parameters.Split('&');
117 foreach (string s in p) {
118 if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix)) {
119 if (s.IndexOf('=') > -1) {
120 string[] temp = s.Split('=');
121 result.Add(new QueryParameter(temp[0], temp[1]));
122 } else {
123 result.Add(new QueryParameter(s, string.Empty));
124 }
125 }
126 }
127 }
128
129 return result;
130 }
131
132 /// <summary>
133 /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
134 /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
135 /// </summary>
136 /// <param name="value">The value to Url encode</param>
137 /// <returns>Returns a Url encoded string</returns>
138 protected string UrlEncode(string value) {
139 StringBuilder result = new StringBuilder();
140
141 foreach (char symbol in value) {
142 if (unreservedChars.IndexOf(symbol) != -1) {
143 result.Append(symbol);
144 } else {
145 result.Append('%' + String.Format("{0:X2}", (int)symbol));
146 }
147 }
148
149 return result.ToString();
150 }
151
152 /// <summary>
153 /// Normalizes the request parameters according to the spec
154 /// </summary>
155 /// <param name="parameters">The list of parameters already sorted</param>
156 /// <returns>a string representing the normalized parameters</returns>
157 protected string NormalizeRequestParameters(IList<QueryParameter> parameters) {
158 StringBuilder sb = new StringBuilder();
159 QueryParameter p = null;
160 for (int i = 0; i < parameters.Count; i++) {
161 p = parameters[i];
162 sb.AppendFormat("{0}={1}", p.Name, p.Value);
163
164 if (i < parameters.Count - 1) {
165 sb.Append("&");
166 }
167 }
168
169 return sb.ToString();
170 }
171
172 /// <summary>
173 /// Generate the signature base that is used to produce the signature
174 /// </summary>
175 /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
176 /// <param name="consumerKey">The consumer key</param>
177 /// <param name="token">The token, if available. If not available pass null or an empty string</param>
178 /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
179 /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
180 /// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
181 /// <returns>The signature base</returns>
182 public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
183 if (token == null) {
184 token = string.Empty;
185 }
186
187 if (tokenSecret == null) {
188 tokenSecret = string.Empty;
189 }
190
191 if (string.IsNullOrEmpty(consumerKey)) {
192 throw new ArgumentNullException("consumerKey");
193 }
194
195 if (string.IsNullOrEmpty(httpMethod)) {
196 throw new ArgumentNullException("httpMethod");
197 }
198
199 if (string.IsNullOrEmpty(signatureType)) {
200 throw new ArgumentNullException("signatureType");
201 }
202
203 normalizedUrl = null;
204 normalizedRequestParameters = null;
205
206 List<QueryParameter> parameters = GetQueryParameters(url.Query);
207 parameters.Add(new QueryParameter(OAuthCallbackKey, "oob"));
208 parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
209 parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
210 parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
211 parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
212 parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
213
214 if (!string.IsNullOrEmpty(token)) {
215 parameters.Add(new QueryParameter(OAuthTokenKey, token));
216 }
217
218 parameters.Sort(new QueryParameterComparer());
219
220 normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
221 if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
222 {
223 normalizedUrl += ":" + url.Port;
224 }
225 normalizedUrl += url.AbsolutePath;
226 normalizedRequestParameters = NormalizeRequestParameters(parameters);
227
228 StringBuilder signatureBase = new StringBuilder();
229 signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
230 signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
231 signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
232
233 return signatureBase.ToString();
234 }
235
236 /// <summary>
237 /// Generate the signature value based on the given signature base and hash algorithm
238 /// </summary>
239 /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
240 /// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
241 /// <returns>A base64 string of the hash value</returns>
242 public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash) {
243 return ComputeHash(hash, signatureBase);
244 }
245
246 /// <summary>
247 /// Generates a signature using the HMAC-SHA1 algorithm
248 /// </summary>
249 /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
250 /// <param name="consumerKey">The consumer key</param>
251 /// <param name="consumerSecret">The consumer seceret</param>
252 /// <param name="token">The token, if available. If not available pass null or an empty string</param>
253 /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
254 /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
255 /// <returns>A base64 string of the hash value</returns>
256 public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters) {
257 return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
258 }
259
260 /// <summary>
261 /// Generates a signature using the specified signatureType
262 /// </summary>
263 /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
264 /// <param name="consumerKey">The consumer key</param>
265 /// <param name="consumerSecret">The consumer seceret</param>
266 /// <param name="token">The token, if available. If not available pass null or an empty string</param>
267 /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
268 /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
269 /// <param name="signatureType">The type of signature to use</param>
270 /// <returns>A base64 string of the hash value</returns>
271 public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
272 normalizedUrl = null;
273 normalizedRequestParameters = null;
274
275 switch (signatureType) {
276 case SignatureTypes.PLAINTEXT:
277 return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
278 case SignatureTypes.HMACSHA1:
279 string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters);
280
281 HMACSHA1 hmacsha1 = new HMACSHA1();
282 hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
283
284 return GenerateSignatureUsingHash(signatureBase, hmacsha1);
285 case SignatureTypes.RSASHA1:
286 throw new NotImplementedException();
287 default:
288 throw new ArgumentException("Unknown signature type", "signatureType");
289 }
290 }
291
292 /// <summary>
293 /// Generate the timestamp for the signature
294 /// </summary>
295 /// <returns></returns>
296 public virtual string GenerateTimeStamp() {
297 // Default implementation of UNIX time of the current UTC time
298 TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
299 return Convert.ToInt64(ts.TotalSeconds).ToString();
300 }
301
302 /// <summary>
303 /// Generate a nonce
304 /// </summary>
305 /// <returns></returns>
306 public virtual string GenerateNonce() {
307 // Just a simple implementation of a random number between 123400 and 9999999
308 return random.Next(123400, 9999999).ToString();
309 }
310
311 }
312}