Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

Username and hashed password authentication on login form C#

$
0
0

Hello I am working on a project, and I am trying to authenticate the user to log in to my website. I do have the password hashed and salt in the database. I can get it to work if the password is in plain text, but now that it is hashed for better security, I am having trouble comparing the Hashed password from when the user signed up, to when they log back in. Here is a look at my code, and any help would be greatly appreciated.  

Also please show some code examples if you can, thanks

protected void LogInClick_Click(object sender, EventArgs e)
{
InsertDatabase LogIn = new InsertDatabase();
GenerateHash HashAndSalt = new GenerateHash();

string GetSalt = HashAndSalt.CreateSalt(10);

PasswordText.Text = HashAndSalt.GenarateHash(PasswordText.Text, GetSalt);

LogIn.LogInAccount(UserText.Text, PasswordText.Text, InvalidLogIn);

Response.Redirect("~/Profile.aspx/");
}



public string CreateSalt(int SaltSize)
{
var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
byte[] buff = new byte[SaltSize];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}

public string GenarateHash(string UserPassword, string salt)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(UserPassword + salt);
System.Security.Cryptography.SHA256Managed PasswordHash = new System.Security.Cryptography.SHA256Managed();

byte[] hash = PasswordHash.ComputeHash(bytes);

return Convert.ToBase64String(hash);
}



public void LogInAccount(string UserName, string UserPassword, Label InvalidLogIn)
{
GenerateHash PasswordHash = new GenerateHash();

connection.ConnectionString = @"connection string";
connection.Open();


string compare = @"Select UserName, UserPassword FROM UserInfo WHERE UserName=@UserName";

//string compare = "select ISNULL(UserName, '') As UserName, ISNULL(UserPassword, '') As UserPassword from UserInfo where UserName= @UserName";

SqlCommand CompareUser = new SqlCommand(compare, connection);

CompareUser.Parameters.AddWithValue("@UserName", UserName);

CompareUser.Parameters.AddWithValue("@UserPassword", UserPassword);

SqlDataReader dr = CompareUser.ExecuteReader();

string GetSalt = PasswordHash.CreateSalt(10);

string Pwd = PasswordHash.GenarateHash(UserPassword, GetSalt);
while(dr.Read())
{
if (UserPassword == Pwd)
{
FormsAuthentication.RedirectFromLoginPage(UserName, true);
}
}

connection.close();



Viewing all articles
Browse latest Browse all 4737

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>