/
Default.aspx.cs
596 lines (486 loc) · 18.1 KB
/
Default.aspx.cs
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection con;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
string querystr;
//string name;
protected void Page_Load(object sender, EventArgs e)
{
//Page.Title = "Save Money";
//HtmlMeta tag = new HtmlMeta();
//tag.Name = "Description";
//tag.Content = "Save money for financial crisis";
//Header.Controls.Add(tag);
//HtmlMeta keywordtag = new HtmlMeta();
//keywordtag.Name = "keywords";
//keywordtag.Content = "Money,Saving,Crisis";
//Header.Controls.Add(keywordtag);
this.theForm.Focus();
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
//Response.Cache.SetNoStore();
visitorlabel.Text = Application["NoOfVisitors"].ToString();
if (!IsPostBack)
{
if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
{
username.Text = Request.Cookies["UserName"].Value;
password.Attributes["value"] = Request.Cookies["Password"].Value;
}
}
//ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "<script language='javascript' >myfunction();</script>");
}
//code for calling of this method from dynamic div to enable controls in page
[System.Web.Services.WebMethod]
public void EnableForm(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Enabled = true;
if (ctrl is Button)
((Button)ctrl).Enabled = true;
//else if (ctrl is DropDownList)
// ((DropDownList)ctrl).Enabled = false;
else if (ctrl is CheckBox)
((CheckBox)ctrl).Enabled = true;
else if (ctrl is HtmlAnchor)
{
HtmlAnchor a = ctrl as HtmlAnchor;
a.Disabled = false;
}
//else if (ctrl is HtmlInputButton)
// ((HtmlInputButton)ctrl).Disabled = true;
//else if (ctrl is HtmlInputText)
// ((HtmlInputText)ctrl).Disabled = true;
//else if (ctrl is HtmlSelect)
// ((HtmlSelect)ctrl).Disabled = true;
//else if (ctrl is HtmlInputCheckBox)
// ((HtmlInputCheckBox)ctrl).Disabled = true;
//else if (ctrl is HtmlInputRadioButton)
// ((HtmlInputRadioButton)ctrl).Disabled = true;
EnableForm(ctrl.Controls);
}
}
protected void submitEventMethod(object sender, EventArgs e)
{
//userlogin(); old code
LoginWithPasswordHashFunction();
}
//new code for hash login with password
private void LoginWithPasswordHashFunction()
{
List<string> salthashList = null;
List<string> namesList = null;
try
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MywebConnection"].ToString();
con = new MySql.Data.MySqlClient.MySqlConnection(connString);
con.Open();
querystr = "SELECT slowHashSalt, Username FROM mydatabase.registertable WHERE Username=?uname";
cmd = new MySqlCommand(querystr, con);
cmd.Parameters.AddWithValue("?uname", username.Text);
reader = cmd.ExecuteReader();
string name = "";
if (reader.HasRows && reader.Read())
{
if (salthashList == null)
{
salthashList = new List<string>();
namesList = new List<string>();
}
string saltHashes = reader.GetString(reader.GetOrdinal("slowHashSalt"));
salthashList.Add(saltHashes);
name = reader.GetString(reader.GetOrdinal("Username"));
namesList.Add(name);
}
reader.Close();
if (salthashList != null)
{
for (int i = 0; i < salthashList.Count; i++)
{
querystr = "";
bool validuser = PasswordStorage.VerifyPassword(password.Text, salthashList[i]);
{
if (validuser == true)
{
if (name == "hardeepsinghnegi")
{
//Session["uname"] = name; old code
Session["uname"] = name;
Response.BufferOutput = true;
Response.Redirect("Login.aspx", false);
}
else
{
Session["uname"] = name;
Response.BufferOutput = true;
Response.Redirect("Guest.aspx", false);
}
}
else
{
username.Text = "";
if (!(chkBoxRememberMe.Checked))
{
chkBoxRememberMe.Checked = false;
}
ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "<script language='javascript' >alertMX('Invalid Username/Password!');</script>");
//ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "myfunctionclick()",true);
//ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "<script language='javascript' >myfunction();</script>");
//new code for ui dialog
//ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "myfunctionclick();",true);
//usererror.Text = "Invalid Username/Password!";
}
con.Close();
}
}
if (chkBoxRememberMe.Checked)
{
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(30);
}
else
{
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);
}
Response.Cookies["UserName"].Value = username.Text.Trim();
Response.Cookies["Password"].Value = password.Text.Trim();
}
else
{
username.Text = "";
if ((chkBoxRememberMe.Checked == true))
{
chkBoxRememberMe.Checked = false;
}
//DisableForm(Page.Controls);
ClientScript.RegisterStartupScript(Page.GetType(), "validationuser2", "<script language='javascript' >disableall();</script>");
ClientScript.RegisterStartupScript(Page.GetType(), "validationuser", "<script language='javascript' >alertMX('Invalid Username/Password !');</script>");
//ClientScript.RegisterStartupScript(Page.GetType(), "validationuser2", "<script language='javascript' >disableall();</script>");
//DisableControls();
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
finally
{
if (cmd != null)
cmd.Dispose();
if (con != null)
con.Close();
}
}
//new code for disabling controls
/* public void DisableForm(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Enabled = false;
if (ctrl is Button)
((Button)ctrl).Enabled = false;
//else if (ctrl is DropDownList)
// ((DropDownList)ctrl).Enabled = false;
else if (ctrl is CheckBox)
((CheckBox)ctrl).Enabled = false;
else if (ctrl is HtmlAnchor)
{
HtmlAnchor a = ctrl as HtmlAnchor;
a.Disabled = true;
}
//else if (ctrl is HtmlInputButton)
// ((HtmlInputButton)ctrl).Disabled = true;
//else if (ctrl is HtmlInputText)
// ((HtmlInputText)ctrl).Disabled = true;
//else if (ctrl is HtmlSelect)
// ((HtmlSelect)ctrl).Disabled = true;
//else if (ctrl is HtmlInputCheckBox)
// ((HtmlInputCheckBox)ctrl).Disabled = true;
//else if (ctrl is HtmlInputRadioButton)
// ((HtmlInputRadioButton)ctrl).Disabled = true;
DisableForm(ctrl.Controls);
}
}
*/
}
/* private void userlogin()
{
try
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MywebConnection"].ToString();
con = new MySql.Data.MySqlClient.MySqlConnection(connString);
con.Open();
querystr = "";
//querystr = "SELECT * FROM mydatabase.registertable WHERE Username='" + username.Text + "' AND Password='" + password.Text + "'";
querystr = "SELECT * FROM mydatabase.registertable WHERE Username=?uname AND Password=?pword";
cmd = new MySqlCommand(querystr, con);
cmd.Parameters.AddWithValue("?uname", username.Text);
cmd.Parameters.AddWithValue("?pword", password.Text);
reader = cmd.ExecuteReader();
name = "";
while (reader.HasRows && reader.Read())
{
name = reader.GetString(reader.GetOrdinal("Username"));
}
if (reader.HasRows)
{
if (name == "hardeep")
{
Session["uname"] = name;
Response.BufferOutput = true;
Response.Redirect("Login.aspx", false);
}
else
{
Session["uname"] = name;
Response.BufferOutput = true;
Response.Redirect("Guest.aspx", false);
}
}
else
{
//valSum.HeaderText = "Invalid Username/Password!";
////passReq.ErrorMessage = "Invalid Password!";
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript' >alertMX('Invalid Username/Password!');</script>");
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowStatus", "javascript:alert('Record is not updated');", true);
}
reader.Close();
con.Close();
}
catch (MySqlException ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
finally
{
if (cmd != null)
cmd.Dispose();
if (con != null)
con.Close();
}
}
}*/
//new code
class InvalidHashException : Exception
{
public InvalidHashException() { }
public InvalidHashException(string message)
: base(message) { }
public InvalidHashException(string message, Exception inner)
: base(message, inner) { }
}
class CannotPerformOperationException : Exception
{
public CannotPerformOperationException() { }
public CannotPerformOperationException(string message)
: base(message) { }
public CannotPerformOperationException(string message, Exception inner)
: base(message, inner) { }
}
class PasswordStorage
{
// These constants may be changed without breaking existing hashes.
public const int SALT_BYTES = 24;
public const int HASH_BYTES = 18;
public const int PBKDF2_ITERATIONS = 64000;
// These constants define the encoding and may not be changed.
public const int HASH_SECTIONS = 5;
public const int HASH_ALGORITHM_INDEX = 0;
public const int ITERATION_INDEX = 1;
public const int HASH_SIZE_INDEX = 2;
public const int SALT_INDEX = 3;
public const int PBKDF2_INDEX = 4;
public static string CreateHash(string password)
{
// Generate a random salt
byte[] salt = new byte[SALT_BYTES];
try
{
using (RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider())
{
csprng.GetBytes(salt);
}
}
catch (CryptographicException ex)
{
throw new CannotPerformOperationException(
"Random number generator not available.",
ex
);
}
catch (ArgumentNullException ex)
{
throw new CannotPerformOperationException(
"Invalid argument given to random number generator.",
ex
);
}
byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTES);
// format: algorithm:iterations:hashSize:salt:hash
String parts = "sha1:" +
PBKDF2_ITERATIONS +
":" +
hash.Length +
":" +
Convert.ToBase64String(salt) +
":" +
Convert.ToBase64String(hash);
return parts;
}
public static bool VerifyPassword(string password, string goodHash)
{
char[] delimiter = { ':' };
string[] split = goodHash.Split(delimiter);
if (split.Length != HASH_SECTIONS)
{
throw new InvalidHashException(
"Fields are missing from the password hash."
);
}
// We only support SHA1 with C#.
if (split[HASH_ALGORITHM_INDEX] != "sha1")
{
throw new CannotPerformOperationException(
"Unsupported hash type."
);
}
int iterations = 0;
try
{
iterations = Int32.Parse(split[ITERATION_INDEX]);
}
catch (ArgumentNullException ex)
{
throw new CannotPerformOperationException(
"Invalid argument given to Int32.Parse",
ex
);
}
catch (FormatException ex)
{
throw new InvalidHashException(
"Could not parse the iteration count as an integer.",
ex
);
}
catch (OverflowException ex)
{
throw new InvalidHashException(
"The iteration count is too large to be represented.",
ex
);
}
if (iterations < 1)
{
throw new InvalidHashException(
"Invalid number of iterations. Must be >= 1."
);
}
byte[] salt = null;
try
{
salt = Convert.FromBase64String(split[SALT_INDEX]);
}
catch (ArgumentNullException ex)
{
throw new CannotPerformOperationException(
"Invalid argument given to Convert.FromBase64String",
ex
);
}
catch (FormatException ex)
{
throw new InvalidHashException(
"Base64 decoding of salt failed.",
ex
);
}
byte[] hash = null;
try
{
hash = Convert.FromBase64String(split[PBKDF2_INDEX]);
}
catch (ArgumentNullException ex)
{
throw new CannotPerformOperationException(
"Invalid argument given to Convert.FromBase64String",
ex
);
}
catch (FormatException ex)
{
throw new InvalidHashException(
"Base64 decoding of pbkdf2 output failed.",
ex
);
}
int storedHashSize = 0;
try
{
storedHashSize = Int32.Parse(split[HASH_SIZE_INDEX]);
}
catch (ArgumentNullException ex)
{
throw new CannotPerformOperationException(
"Invalid argument given to Int32.Parse",
ex
);
}
catch (FormatException ex)
{
throw new InvalidHashException(
"Could not parse the hash size as an integer.",
ex
);
}
catch (OverflowException ex)
{
throw new InvalidHashException(
"The hash size is too large to be represented.",
ex
);
}
if (storedHashSize != hash.Length)
{
throw new InvalidHashException(
"Hash length doesn't match stored hash length."
);
}
byte[] testHash = PBKDF2(password, salt, iterations, hash.Length);
return SlowEquals(hash, testHash);
}
private static bool SlowEquals(byte[] a, byte[] b)
{
uint diff = (uint)a.Length ^ (uint)b.Length;
for (int i = 0; i < a.Length && i < b.Length; i++)
{
diff |= (uint)(a[i] ^ b[i]);
}
return diff == 0;
}
private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes)
{
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt))
{
pbkdf2.IterationCount = iterations;
return pbkdf2.GetBytes(outputBytes);
}
}
}