Query regarding password hashing. Cannot log in - c#

i am trying to encrypt a password and be able to log in with it. here is my hash code inside my businesslayer folder under shopping cart class.
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
and here is my registration code where i included the hash with the password. i am successful in registering an account and having an encrypted password in my database with this:
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
However, when i try to log in with the password that i have registered, its not letting me in. here is the code:
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString();
if (password == BusinessLayer.ShoppingCart.CreateSHAHash(txtPassword.Text))
{
Session["New"] = txtUser.Text;
Response.Write("<script>alert('Logged In')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
what am i missing here? thank you

Related

c# validating login with sql database

protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
lblMessage.Text = "Invalid login credentials";
}
else
{
Response.Redirect("SubmitViewingRequest.aspx");
}
}
the codes above doesn't validate the email address and password with the database. any email address and password entered is considered correct. can i get help? thank you!
Change your if condition
if (result.Tables["Login"].Rows.Count > 0) // For Successfully Login
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else // For Invalid User credentials
{
lblMessage.Text = "Invalid login credentials";
}
This happens when we mistakenly put if conditions in reverse order. Please change your code with if conditions replaced like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else
{
lblMessage.Text = "Invalid login credentials";
}
}
Hope this helps

BCrypt Verifying password against password in database

I am trying to verify a hashed password in my database which has been hashed with BCrypt.
I have two web forms, a login page and registration page.
In the registration page i create the hash, verify the hash and insert it into the database. Works fine.
In the login page i select the hashed password from the database and compare it with the submitted password from the text box.
I seem to be having trouble when verifying the hash in the database against the submitted password, i don't know what is going wrong.
Here is the registration page code:
protected void registerbutton_Click(object sender, EventArgs e)
{
string myPassword = passwordtextbox.Text;
string mySalt = BCryptHelper.GenerateSalt();
string myHash = BCryptHelper.HashPassword(myPassword, mySalt);
bool doesPasswordMatch = BCryptHelper.CheckPassword(myPassword, myHash);
if (doesPasswordMatch == true)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Users (Username, Password, FirstName, LastName) VALUES (#username, #password, #firstname, #lastname)", conn))
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar).Value = usernametextbox.Text;
cmd.Parameters.Add("#password", SqlDbType.Char).Value = myHash;
cmd.Parameters.Add("#firstname", SqlDbType.NVarChar).Value = firstnametextbox.Text;
cmd.Parameters.Add("#lastname", SqlDbType.NVarChar).Value = lastnametextbox.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
registerlabel3.Text = myHash;
}
}
else
{
registerlabel3.Text = "Error";
}
}
Here is the login page code:
protected void loginbutton_Click(object sender, EventArgs e)
{
const string query = "SELECT Username, Password FROM dbo.Users WHERE Username = #username";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar).Value = usernametextbox.Text;
conn.Open();
//string hashedPassword = BCrypt.Net.BCrypt.HashPassword(passwordtextbox.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var passwordInDb = reader.GetString(1);
Label3.Text = "submitted = " + passwordtextbox.Text;
Label4.Text = "database hash = " + passwordInDb;
if(BCryptHelper.CheckPassword(passwordtextbox.Text, reader.GetString(1)))
{
//login
loginlabel.Text = "Success";
}
else
{
loginlabel.Text = "Error";
}
}
}
}
}
Help and Feedback is appreciated.
When writing to the database, try:
protected void registerbutton_Click(object sender, EventArgs e)
{
....
cmd.Parameters.Add("#password", SqlDbType.NVarChar).Value = myHash;
....
}
Set the database field to CHAR(60)
I set my database field where the hashed password is stored to CHAR(60) and now it works.
Why it has to be specifically CHAR(60), i don't know, but it works.
Would be nice if this could be explained.

user and password authentication asp.net

The user and password are correct but are returning as incorrect. What can it be?
Importantly, the password and encrypted in md5.
public static bool logarUsuario(string user, string pw)
{
try
{
const string checkUser = "SELECT COUNT(*) FROM tbUsuario WHERE userName = '#user'";
SqlConnection con = Banco.con();
con.Open();
SqlCommand cmd = new SqlCommand(checkUser, con);
int temp = Convert.ToInt32(cmd.ExecuteNonQuery().ToString());
cmd.Parameters.AddWithValue("#user", user);
con.Close();
if (temp == 1)
{
con.Open();
string checkPw = "SELECT pw FROM tbUsuario WHERE userName = '#user'";
SqlCommand passConn = new SqlCommand(checkPw, con);
cmd.Parameters.AddWithValue("#user", user);
string password = passConn.ExecuteScalar().ToString();
Registrar criptografia = new Registrar();
if (password == pw)
{
return true;
}
}
}
catch (SqlException ex)
{
Console.WriteLine("Erro " + ex.Message);
}
return false;
}
Within the btnLogar click event:
Already checked the database and the username and password are correct, but this as incorrect password.
protected void bntLogar_Click(object sender, EventArgs e)
{
Registrar criptografia = new Registrar();
if (Login.logarUsuario(txtUser.Text, criptografia.CriptografiaMD5(txtSenha.Text)))
{
//Cria um cookie do lado do servidor
HttpCookie cookie = new HttpCookie("estado", "conectado");
//Define a validade do cookie (10 dias a partir de hoje)
cookie.Expires = DateTime.Now.AddMonths(12);
//Envia o cookie para o cliente
Response.Cookies.Set(cookie);
//Redireciona para a pagina inicial
Response.Redirect("Admin.aspx");
}
else
{
lblErro.Text = "Usuário ou Senha Incorretos";
lblErro.Visible = true;
lblErro.CssClass = "alert alert-danger";
}
}
'#user' is incorrect. Do not surround a parameter name with a single quote. It should look like
SELECT pw FROM tbUsuario WHERE userName = #user
Also MD5 is no longer considered secure, I suggest using SHA-256.
You can do this with a single SELECT statement
public static bool logarUsuario(string user, string pw)
{
const string checkUser =
#"SELECT COUNT(*) FROM tbUsuario
WHERE userName = #u AND pw = #p";
using (SqlConnection con = Banco.con())
{
con.Open();
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.Parameters.AddWithValue("#u", user);
cmd.Parameters.AddWithValue("#p", pw);
return 1 == (int) cmd.ExecuteNonQuery();
}
}
This assumes that pw is already hashed.

Check if username exists before pressing submit button

i have this code-behind:
protected void cmdSave_Click(object sender, EventArgs e)
{
string sFilePath = Server.MapPath("Database3.accdb");
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=#username", Conn);
myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
int totalRegistos = (int)myCommand.ExecuteScalar();
if (totalRegistos > 0)
{
// user already answered
lblInfo0.Text = "The user already asnwered";
}
else
{
// the user didn't asnwered
string insertCmd = "INSERT INTO colaborador(Empresa,Empresa2,Telemovel,username) VALUES (#Empresa,#Empresa2,#Telemovel,#username)";
// insere na tabela colaborador os campos empresa, empres2, user os valores #
{
OleDbCommand myCommand2 = new OleDbCommand(insertCmd, Conn);
myCommand2.Parameters.AddWithValue("#Empresa", empresa.Text);
myCommand2.Parameters.AddWithValue("#Empresa2", empresa2.Text);
myCommand2.Parameters.AddWithValue("#Telemovel", telemovel.Text);
myCommand2.Parameters.AddWithValue("#username", HttpContext.Current.User.Identity.Name);
Response.Write(myCommand.ExecuteNonQuery());
lblInfo.Text = "Data saved!";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
}
this working fine with no errors and save into db also if the username exist say a message "user already answered"
however i need press submit button.
there's any way to say the message (if the username already exist) before field the text.box? how can i change my code to do that?
if (!IsPostBack)
{
string sFilePath = Server.MapPath("Database3.accdb");
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=#username", Conn);
myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
int totalRegistos = (int)myCommand.ExecuteScalar();
if (totalRegistos > 0)
{
// Já registado
lblInfo0.Text = "O username já existe na base de dados";
empresa.Enabled = false;
empresa2.Enabled = false;
telemovel.Enabled = false;
cmdSave.Visible = false;
}
}
}

Login to SQL Server database not working

I am trying to make a log in page in C# web page. I have written that code which I think is correct. The user supposed to key in the correct username and password. Before I go any further into modifying after success log in I temporarily set the label 1 to show me whether it's correct or not. However it doesn't work and every time I tried to key in the correct data, it always show "failed".
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=localhost;Initial Catalog=SeminarDB; Integrated security=true;");
try
{
con.Open();
string str = "select * from Member where Username='" + signintext.Text + "' and Password='" + passwordtext.Text + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
string login = signintext.Text;
string pwd = passwordtext.Text;
while (dr.Read())
{
if ((dr["Username"].ToString() == login) && (dr["Password"].ToString() == pwd))
{
Label1.Text = "success!";
visibl = true;
}
else
{
Label1.Text = "failed!";
}
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Try this, hope it works
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=localhost;Initial Catalog=SeminarDB; Integrated security=true;");
try
{
con.Open();
string str = "select * from Member where Username='" + signintext.Text + "' and Password='" + passwordtext.Text + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
Label1.Text = "success!";
visibl = true;
}
else
{
Label1.Text = "failed!";
}
con.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Try this simple method..
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=localhost;Initial Catalog=SeminarDB; Integrated security=true;");
try
{
con.Open();
string str = "select count(*) from Member where Username='" + signintext.Text + "' and Password='" + passwordtext.Text + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
string login = signintext.Text;
string pwd = passwordtext.Text;
while (dr.Read())
{
if ((dr[0] > 0)
{
Label1.Text = "success!";
}
else
{
Label1.Text = "failed!";
}
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}

Categories

Resources