-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleSSO.cs
More file actions
310 lines (275 loc) · 11.2 KB
/
SimpleSSO.cs
File metadata and controls
310 lines (275 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/***************************************************************************
* Copyright %CreateDate% Opher Shachar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**************************************************************************/
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Com.Ladpc.Util.SSO
{
public class SimpleSSO
{
public readonly Encoding charEncoding;
public readonly HMAC hmac;
public readonly bool resEncAll;
public readonly string separator;
public readonly EncType resEncoding;
public readonly TimeSpan lifetime;
public enum EncType { HEXSTRING, BASE64 };
/// <summary>
/// Constructor that takes all user settable options. Note that the given
/// <paramref name="hmac"/> needs to be initialized with your secret key.
/// </summary>
/// <param name="charEncoding">The character encoding of the user data
/// provided to this class's methods.</param>
/// <param name="hmac">An instance of <see cref="HMAC"/> algorithem
/// initialized with your secret key.</param>
/// <param name="resEncAll">Set to <c>False</c> to text-encode just the
/// hash-mac. Otherwise, set to <c>True</c>, to text-encode a complete
/// string representation of the form: "user-data:timestamp~hmac".<br/>
/// Where "user-data" is a ':' joined string of the user-data elements,
/// ':' is the 'separator' and '~' is a blank (shown for clarity).</param>
/// <param name="separator">A separator char for concatenating strings
/// into a single token.</param>
/// <param name="resEncoding">Either <c>Base64</c> or <c>Hex String</c>
/// representation of the (partialy) binary result to returm.</param>
/// <param name="lifetime">A <c>TimeSpan</c> for the validity of the
/// created token.</param>
public SimpleSSO(Encoding charEncoding, HMAC hmac, bool resEncAll, char separator, EncType resEncoding, TimeSpan lifetime)
{
if (charEncoding == null || hmac == null)
throw new ArgumentNullException();
else if (!Enum.IsDefined(typeof(EncType), resEncoding))
throw new ArgumentOutOfRangeException("resEncoding");
this.charEncoding = charEncoding;
this.hmac = hmac;
this.resEncAll = resEncAll;
this.separator = separator.ToString();
this.resEncoding = resEncoding;
this.lifetime = lifetime;
}
/// <summary>
/// Constructor that creates an instance with these parameters:
/// <list type="bullet">
/// <item><description><c>UTF8</c> Encoding,</description></item>
/// <item><description>an <see cref="HMACSHA256"/> initialized with the
/// provided <paramref name="key"/>,</description></item>
/// <item><description>text-encoding the hmac only</description></item>
/// <item><description>use ':' as separator</description></item>
/// <item><description>result encoding as hex string</description></item>
/// <item><description>Five minutes expiration time</description></item>
/// </list>
/// </summary>
/// <param name="key">The secret key phrase.</param>
public SimpleSSO(string key) : this(
Encoding.UTF8,
new HMACSHA256(Encoding.UTF8.GetBytes(key)),
false,
':',
EncType.HEXSTRING,
TimeSpan.FromMinutes(5)) { }
public string[] CreateTokens(string data, params string[] more)
{
// Note: Correctness depens on encoding not using ':',
// i.e. if we allow ASCII85 this call may fail.
return CreateToken(data, more).Split(separator[0]);
}
public string CreateToken(string data, params string[] more)
{
if (String.IsNullOrEmpty(data))
throw new ArgumentNullException("data");
string message = CreateMessage(data, more);
byte[] ba = charEncoding.GetBytes(message);
byte[] hash = hmac.ComputeHash(ba);
if (resEncAll)
{
return Encode(ConcatenateArrays(ba, hash));
}
else
{
return message + separator + Encode(hash);
}
}
public bool IsValid(string token, params string[] more)
{
return DecodeData(token, more).Length > 0;
}
public string[] DecodeData(string token, params string[] more)
{
try
{
return Validate(token, more);
}
catch (ArgumentException) { }
catch (CryptographicException) { }
catch (FormatException) { }
catch (System.Security.Authentication.InvalidCredentialException) { }
catch (TimeoutException) { }
return new string[0];
}
public string[] Validate(string token, params string[] more)
{
if (String.IsNullOrEmpty(token))
throw new ArgumentNullException("token");
else if (more.Length == 1)
throw new ArgumentException("There may be either one token or three or more tokens.", "more");
string data = null,
encodedText;
byte[] ba, hash;
if (more.Length == 0)
{
// Note: Correctness depens on encoding not using ':',
// i.e. if we allow ASCII85 this call may fail.
int pos = token.LastIndexOf(separator) + 1;
if (pos == token.Length)
{
throw new ArgumentException("No hash found in token.", "token");
}
else if (pos == 1)
{
throw new ArgumentException("No user data found in token.", "token");
}
else if (pos > 1)
{
encodedText = token.Substring(pos);
data = token.Substring(0, pos - 1);
}
else // pos == 0
{
encodedText = token;
}
}
else
{
encodedText = more[more.Length - 1];
data = ConcatenateStrings(token, more, 0, more.Length - 1);
}
if (data == null) // A single encoded token
{
ba = Decode(encodedText);
if (ba.Length <= hmac.HashSize / 8)
throw new ArgumentException("Invalid token.", "token");
hash = new byte[hmac.HashSize / 8];
Array.Copy(ba, ba.Length - hash.Length, hash, 0, hash.Length);
Array.Resize(ref ba, ba.Length - hash.Length);
data = charEncoding.GetString(ba);
}
else
{
hash = Decode(encodedText);
if (hash.Length != hmac.HashSize / 8)
throw new ArgumentException("Invalid token.", "token");
ba = charEncoding.GetBytes(data);
}
if (!ArrayEquals(hmac.ComputeHash(ba), hash))
throw new System.Security.Authentication.InvalidCredentialException();
else if (IsExpired(data))
throw new TimeoutException("Token expired.");
return data.Split(separator[0]);
}
private string CreateMessage(string data, string[] more)
{
string ms = Math.Truncate((DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString();
return ConcatenateStrings(data, more, 0, more.Length) + separator + ms;
}
private string ConcatenateStrings(string data, string[] more, int startIndex, int count)
{
StringBuilder sb = new StringBuilder(data);
if (more.Length > 0)
sb.Append(separator)
.Append(String.Join(separator, more, startIndex, count));
return sb.ToString();
}
private byte[] ConcatenateArrays(params byte[][] arrays)
{
int pos = 0;
foreach (var arr in arrays)
{
pos += arr.Length;
}
byte[] temp = new byte[pos];
pos = 0;
foreach (var arr in arrays)
{
Array.Copy(arr, 0, temp, pos, arr.Length);
pos += arr.Length;
}
return temp;
}
private string Encode(byte[] ba)
{
switch (resEncoding)
{
case EncType.HEXSTRING:
StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (var b in ba)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
case EncType.BASE64:
return Convert.ToBase64String(ba);
default:
break;
}
// We should never get here
throw new NotSupportedException();
}
private byte[] Decode(string encodedText)
{
switch (resEncoding)
{
case EncType.HEXSTRING:
byte[] ba = new byte[encodedText.Length / 2];
for (int i = 0; i < ba.Length; i++)
{
ba[i] = (byte)(HexValue(encodedText[2 * i]) << 4 + HexValue(encodedText[2 * i + 1]));
}
return ba;
case EncType.BASE64:
return Convert.FromBase64String(encodedText);
default:
break;
}
// We should never get here
throw new NotImplementedException();
}
private int HexValue(char c)
{
int b = c - '0';
if (b > 9) b -= 7;
return b;
}
private bool ArrayEquals(byte[] a1, byte[] a2)
{
if (ReferenceEquals(a1, a2))
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
for (int i = 0; i < a1.Length; i++)
if (a1[i] != a2[i])
return false;
return true;
}
private bool IsExpired(string data)
{
int pos = data.LastIndexOf(separator) + 1;
int ms = Convert.ToInt32(data.Substring(pos));
return (DateTime.Now - new DateTime(1970, 1, 1) - lifetime).TotalMilliseconds > ms;
}
}
}