Invalid Column name 'password' - c#

protected void Button1Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["UserThomasConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from RegisterFormTable where User_Name='" + TextBox1Username.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = "select password from RegisterFormTable where User_Name='" + TextBox1Username.Text + "'";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
string password = passComm.ExecuteScalar().ToString();
password = string.Join("", password.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
if (password == TextBox2Password.Text)
{
Session["New"] = TextBox1Username.Text;
Response.Write("Password is correct");
}
else
{
Response.Write("Password is not correct");
}
}
else
{
Response.Write("Username is not correct");
}
conn.Close();
}
string password = passComm.ExecuteScalar().ToString();
This is line code that is error
Please help. what should I do?

using BCrypt.Net; // Add this package via NuGet
protected void Button1Login_Click(object sender, EventArgs e)
{
//Note the different column name. You'll have to change the table to use a hash instead of a raw password!
// You also have to change the user creation and password change code to create the hash values instead of saving the raw text
// THIS IS IMPORTANT!!!
string SQL = "select passwordHash from RegisterFormTable where User_Name= #UserName";
using var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["UserThomasConnectionString"].ConnectionString);
using var com = new SqlCommand(SQL, conn);
// Use the actual column type and length from the database here
com.Parameters.Add("#UserName", SqlDbType.NVarChar, 25).Value = TextBox1Username.Text;
conn.Open();
string hash = com.ExecuteScalar() as string;
if (string.IsNullOrWhitespace(hash))
{
Response.Write("Username is not correct");
}
else if (BCrypt.Verify(TextBox2Password.Text, hash))
{
Session["New"] = TextBox1Username.Text;
Response.Write("Password is correct");
}
else
{
Response.Write("Password is not correct");
}
}

Related

Encrypting and decrypt password to login

I am trying to make a login and register for my website. I have used hash to encrypt the password but im struggling to log back in. The code for the login page is below
This is what ive used to encrypt the password
public string ToSHA2569(string value)
{
SHA256 sha256 = SHA256.Create();
byte[] hashData = sha256.ComputeHash(Encoding.Default.GetBytes(value));
StringBuilder returnValue = new StringBuilder();
for (int i = 0; i < hashData.Length; i++)
{
returnValue.Append(hashData[i].ToString());
}
return returnValue.ToString();
}
This is my register page
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection sqlcon = new SqlConnection(connectionString))
{
sqlcon.Open();
SqlCommand cmd = new SqlCommand("UserRegister", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", txtName.Text.Trim());
cmd.Parameters.AddWithValue("#Email", txtEmail.Text.Trim());
cmd.Parameters.AddWithValue("#Password", ToSHA2569(txtPassword.Text.Trim()));
cmd.Parameters.AddWithValue("Created", DateTime.Now);
cmd.ExecuteNonQuery();
lblMessage.Text = "You have registered succussfully";
}
}
catch (Exception ex)
{
lblWrong.Text = "Something went wrong please try again later";
}
}
}
This is my login page
i think there is something wrong here. Is it easier to use an encryption key instead of hash?
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection sqlcon = new SqlConnection(connectionString))
{
sqlcon.Open();
string checkPasswordQuery = "select Password from [dbo.Register] where Username ='" + ToSHA2569(txtEmail.Text) + "'";
SqlCommand passcom = new SqlCommand(checkPasswordQuery, sqlcon);
if (txtPassword.Text == ToSHA2569(txtPassword.Text))
{
Response.Redirect("default.aspx");
}
else
{
Response.Write("Password is not correct");
}
}
}
catch
{
lblWrong.Text = "Something went wrong please try again later";
}
}
string checkPasswordQuery = "select Password from [dbo.Register] where Username ='" + ToSHA2569(txtEmail.Text) + "'";
What is the reason for encrypting the email here?
Try changing to following where you are encrypting the password entered with what is in database.
if (checkPasswordQuery == ToSHA2569(txtPassword.Text))

How can I make my Login Form Object-Oriented

My problem is I don't know how to call the textboxes and buttons to my class from my form login. So I decided to put my codes inside my btnLogin events. How can I make my codes oop style?
private void btnLogin_Click(object sender, EventArgs e)
{
int count = 0;
Connection connection = new Connection();
string sql = "SELECT * FROM tbl_Account WHERE Username='" + txtUserName.Text + "' and Password='" + txtPassword.Text + "'";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
conn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
count++;
}
if (count == 1)
{
MessageBox.Show("Login Successfully!");
this.Hide();
main.showMeForm4(this);
}
else
{
txtPassword.Focus();
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = "";
txtPassword.Text = "";
}
conn.Close();
}
Put your business logic to a separate class:
Do not concat SQL query (SQL Injections).
BusinessLogic class
public bool Authorize(string userName, string userPassword)
{
Connection connection = new Connection();
string sql = "SELECT Count(*) FROM tbl_Account WHERE Username=#userName and Password=#userPassword";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#userName",userName);
cmd.Parameters.AddWithValue("#userPassword",userPassword);
int count = 0;
try
{
conn.Open();
int count = int.TryParse(cmd.ExecuteScalar().ToString());
}
finally
{
con.Close();
}
return count==1;
}
Call it:
BusinessLogic businessLogic = new BusinessLogic();
private void btnLogin_Click(object sender, EventArgs e)
{
if (businessLogic.Authorize(txtUserName.Text, txtPassword.Text)
{
MessageBox.Show("Login Successfully!");
this.Hide();
main.showMeForm4(this);
}
else
{
txtPassword.Focus();
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = "";
txtPassword.Text = "";
}
}

Change Password issues in ASP.Net

Hi i'm trying to changing the password so the user's password is update on the database. For example, i want the user Mary Tan's password to be changed from 12345 to 54321. But if affect the rest of the user's password. I really idk how to fix it.
Output:
click here
Table
database table
My Code:
protected void btnChangePassword_Click(object sender, EventArgs e)
{
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd";
if (Session["Username"] != null)
{
sql += " WHERE UserName='" + Session["Username"].ToString() + "'";
}
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
conn.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch(Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
Which means your Session["Username"] is null at this moment of execution. Hence the Where condition will skip and update all rows. And What is the Function of Reader There? It is not necessary, The ExecuteNonQuery is enough to do this Job and it will returns the number of rows affected. So you can do this in the following way:
string connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
if (Session["Username"] != null)
{
string sql = "UPDATE Staff Set Password=#NewPwd WHERE UserName=#Username";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#Username", Session["Username"]);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
}
}
else
{
// Show message that Session is Empty Can't Proceed
}
Important Note :- Don't save password as plain Text, Hash and salt them
Change your method like this (check Session in the start)
protected void btnChangePassword_Click(object sender, EventArgs e)
{
if (Session["Username"] == null)
{
//User is not logged-in. Display message or handle
return;
}
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd Where UserName = #UserName";
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#UserName", Session["Username"].ToString());
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}

Else doesn't work in reader using c#

When I enter user name and password, it logs in successfully and also opens desired field but when I enter wrong name or password (not saved in DB) it shows nothing actually it should encounter "else" this is the code
private void signin_button_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:/Student_Managment_System/SMS1.mdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
string usrname = name_textBox.Text;
string passwd = pass_textBox.Text;
OleDbCommand cmd1 = new OleDbCommand("select * from Manager where Name='" + usrname + "' and Passwd='" + passwd + "'");
OleDbDataReader Reader = cmd1.ExecuteReader();
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
else
{
MessageBox.Show("Inviled User name or password");
}
}
myConnection.Close();
}
Your else statement isn't executed because there are no values to read when an invalid username or password is entered. You need to check if your reader has any rows. See here
Code
//Are there any rows
if(Reader.HasRows)
{
//If so read them
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
}
}
else
{
MessageBox.Show("Inviled User name or password");
}

Hashed password is not recognized after changing it

I have hased my password right there on in the registration.aspx. having this code in my business layer:
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 this code in the register page:
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
Having the codes above, the password are being hashed in the DB and it is working fine when I log in with this code:
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
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");
}
However when I change it having this code in my changepassword.aspx, its not letting me in with my new password.
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "select * from UserData ";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
if (BusinessLayer.ShoppingCart.CreateSHAHash(txt_cpassword.Text) == reader["Password"].ToString())
{
up = 1;
}
}
reader.Close();
con.Close();
if (up == 1)
{
con.Open();
str = "update UserData set Password=#Password where UserName='" + Session["New"].ToString() + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 50));
com.Parameters["#Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txt_npassword.Text);
com.ExecuteNonQuery();
con.Close();
lbl_msg.Text = "Password changed Successfully";
}
else
{
lbl_msg.Text = "Please enter correct Current password";
}
}
What am I missing here?
Check if the 50 truncates the hash.
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 50));
On a sidenote i see that your solution is very open to SQL injection.
"select Password from UserData where Username ='" + txtUser.Text + "'";
A user can write sql statements in the textbox, and hijack your database, create his own tables or drop the whole database. You should always parameterize the queries. I see that you did that to the Update statement, but you should consider doing it for all of your variables.
This quickly creates a lot of code, so i would also consider making an SQL wrapper, that wraps in all of the things you repeat. When you are done refactoring it could look something like this:
var sql = new SqlWrapper("select Password from UserData where Username = #username", txtUser.Text);
var dataSet = sql.Execute();
Then you can hide all of your connectionstring, commands++ behind this wrapper and only tell the wrapper what you actually care about.
You should also consider using a salt for your password. If you and I have the same password, the hash will be the same. A salt will fix this problem.
A good article about password security -> https://crackstation.net/hashing-security.htm

Categories