Hash encrypting password when inserting into database - c#

I'm doing an application for school and I'm in need of help in encrypting passwords when inserting them into my users database.I'm programming in c# programming language and i'm using MS server 2008 R2 for manipulating my database. I'm thinking of doing a HASH encryption and I would love if someone helped me out.
Here's my code for inserting data into database :
using (SqlConnection con = new SqlConnection("Data Source=HRC0;Initial Catalog=users;Integrated Security=True")) //MLHIDE
using (SqlCommand sc = new SqlCommand("if NOT exists (select * from users where UserName = #username) insert into users (userName, password) values(#userName, #password)", con))
{
con.Open();
sc.Parameters.AddWithValue("#username", korisnik.Text);
sc.Parameters.AddWithValue("#password", pass.Text);
int o = sc.ExecuteNonQuery();
if (o == -1)
{
MessageBox.Show(Ulaz.Properties.Resources.Niste_ubačeni_u_bazi_korisničk);
this.Hide();
new Registracija().Show();
}
else
{
MessageBox.Show(Ulaz.Properties.Resources.Ubačeni_ste_u_bazi);
con.Close();
this.Hide();
new Form1().Show();
}
and here's my code for login check :
SqlConnection con = new SqlConnection("Data Source=HRC0;Initial Catalog=users;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select * from users where userName='" + user.Text + "' and password='" + pass.Text + "'", con); //MLHIDE
con.Open();
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
ImeUsera = user.Text;
new UserMode().Show();
this.Hide();
}
else
{
this.Hide();
new LoginFail().Show();
}
}
I used some Multi-Language add-on so he converted my strings into ''Ulaz.Properties.Resources.'' and simmilar.

To hash a string of text you could use a function like this
private string GetHashedText(string inputData)
{
byte[] tmpSource;
byte[] tmpData;
tmpSource = ASCIIEncoding.ASCII.GetBytes(inputData);
tmpData = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
return Convert.ToBase64String(tmpData);
}
and apply to your user input. Then store the result in the database. At login you reapply the hash function to the typed password and check the result against the stored value.
So in your insert code you write
sc.Parameters.AddWithValue("#password", GetHashedText(pass.Text));
and in your check
....
SqlCommand cmd = new SqlCommand("select * from users where userName=#user and password=#pass", con);
con.Open();
cmd.Parameters.AddWithValue("#user",user.Text);
cmd.Parameters.AddWithValue("#pass", GetHashedText(pass.Text));
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
.....
Remember that Hashing is not reversible, so you cannot retrieve the original password from the hashed text. You apply the Hash function to your text and store it as a base64 string. If your user forgets the password, you need to reset it to a known value. There is no way to tell him the original password.
By the way, why in your check you don't use parameters as you do in the insert code? Never use string concatenation to build sql queries. Even if you're in a hurry to finish the job

Related

Trying to update hashed password c#

i'm trying to update my database with a new hashed password on asp.net with a change password form,but it isn't working nor giving me errors.
I'm using bcrypt for hashing.Registration and Login are working just fine,but changing the hashed password is difficult.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
con.Open();
//Select
string query = "select password from Users where name=#name";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#password", txtOld.Text.Trim());
cmd.Parameters.AddWithValue("#name", LblUser.Text);
//Update
try {
string queryupdate = "UPDATE Users SET password=#newpassword WHERE name=#name";
SqlCommand cmd1 = new SqlCommand(queryupdate, con);
string salt = BCr.BCrypt.GenerateSalt(12);
// if you look at the hashed password, notice that it's prepended with the salt generated above
string hashedPassword = BCr.BCrypt.HashPassword(txtConfirm.Text.Trim(), salt);
cmd1.Parameters.AddWithValue("#name", LblUser.Text);
cmd1.Parameters.AddWithValue("#newpassword", hashedPassword);
cmd1.Parameters.AddWithValue("#password", txtOld.Text.Trim());
cmd1.ExecuteNonQuery();
LblUser.Text = "Password changed successfully";
LblUser.ForeColor = System.Drawing.Color.Green;
}
catch(Exception ex)
{
LblUser.Text = "Something Went Wrong";
LblUser.ForeColor = System.Drawing.Color.Red;
}
I'm assuming you're using the newer version of the bcrypt library https://www.nuget.org/packages/BCrypt.Net-Next/ rather than the old one with bugs.
Firstly don't generate the salt yourself this is dealt with in the library.
You can generate a new password hash securely by simply calling
var myNewHash = BCrypt.ValidateAndReplacePassword(currentPassword, currentHash, newPassword);
This of course forces the process to require the user to enter their current password in order to change their password (this is best practice).
If you're doing this in the sense of a password reset you should hash the password using
var myNewHash = BCrypt.HashPassword("newpassword");
As documented at the start of the readme https://github.com/BcryptNet/bcrypt.net
As for the SQL element; I'd consider using EF or Dapper.Net over direct ADO manipulation. SQL parameterisation isn't foolproof protection against SQLI Examples of SQL injection even when using SQLParameter in .NET?
If you're using ADO though make sure you specify your parameter types ala
var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
var query = "Select * From Products Where ProductID = #ProductID";
using (var conn = new SqlConnection(connect))
{
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#ProductID", SqlDbType.Int);
cmd.Parameters["#ProductID"].Value = Convert.ToInt32(Request["ProductID"]);
conn.Open();
conn.Open();
//Process results
}
}
Disclaimer: I'm the author of the listed repo
Code sample for ADO from https://www.mikesdotnetting.com/article/113/preventing-sql-injection-in-asp-net

How to validate Password and Username for website in c#

I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}

C# Database Log In form

I want to create a Registration and Log In form on Visual Studio 2010 (with Visual C#).
I have created Service-Based Database and one table. I can insert data into the table (at the registration form), but I cannot figure out how to log in the user.
I have a very simple Log In Form (just fields for username and password) and a 'Log In' Button. I do not really know how to check if the password and the username (that exist in my database) match. Here is what I have so far:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" & textBox2.Text != "")
{
cn.Open(); // cn is the Sqlconnection
cmd.Parameters.AddWithValue("#Username", textBox1.Text); // cmd is SqlCommand
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
if (cmd.CommandText == "SELECT * FROM Table1 WHERE username = #Username AND password = #Password")
{
MessageBox.Show("Loggen In!");
this.Close();
}
cn.Close();
}
}
You need to Execute the query to know if the information exists in the database
if (textBox1.Text != "" & textBox2.Text != "")
{
string queryText = #"SELECT Count(*) FROM Table1
WHERE username = #Username AND password = #Password";
using(SqlConnection cn = new SqlConnection("your_connection_string"))
using(SqlCommand cmd = new SqlCommand(queryText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
MessageBox.Show("Loggen In!");
else
MessageBox.Show("User Not Found!");
}
}
I have also changed something in your code.
Changed the query text to return just the count of the users with the
specific username and account and be able to use ExecuteScalar
Enclosed the creation of the SqlConnection and SqlCommand in a using
statement to be sure to dispose these objects at the end of the
operation
I also recommend to change the the way in which you store the password.
Store, in the password field, an hash not the clear password. Then pass to the database the same hash and compare this against the content of the database field.
In this way, the password is known only to your user, not by you or by any passersby that looks at the database table
SqlConnection con = new SqlConnection("connection_string");
SqlCommand cmd = new SqlCommand("select Count(*) from [dbo].[Table] where uname=#uname and password=#password");
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#uname", uname.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
int Result=(int)cmd.ExecuteScalar();
if (Result > 0)
{
Response.Redirect("welcome.aspx");
}
else
{
Response.Redirect("register.aspx");
}

MySQL Password Login Code?

I'm trying to do a Login code in C# with MySQL. Basically the user enters a username and password then the code checks the database if the the password is correct. I'm having trouble getting the code to read from the data base... Here is where I'm at.
public string strUsername;
public string strPassword;
//Connect to DataBase
MySQLServer.Open();
//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
string TruePass = mySQLReader.GetString(1);
if (strPassword == TruePass)
{
blnCorrect = true;
//Get Player Data
}
}
MySQLServer.Close();
From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. I am still fairly new to MySQL so any help would be Great.
Non-numeric field value must be enclosed with single quote.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
but you have to use Parameters to prevent SQL Injection.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =#username";
mySQLCommand.Connection=MySQLServer;
mySQLCommand.Parameters.AddWithValue("#username",strUsername);
string con_string = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
SqlConnection Con = new SqlConnection(con_string);
SqlCommand Com = new SqlCommand(query, Con);
Con.Open();
SqlDataReader Reader;
Reader = Com.ExecuteReader();
if (Reader.Read())
{
lblStatus.Text="Successfully Login";
}
else
{
lblStatus.Text="UserName or Password error";
}
Con.Close();
As AVD said you should use parameters to prevent sql injection....

How can I get a username and password from my database in C#?

I have the following code in my btn_click event:
Sqlconnection con = new Sqlconnection("server=.;database=bss;user id=ab;pwd=ab");
con.open();
SqlCommand cmd = new Sqlcommand("select * from login where username='"
+ txt4name.Text + "' and pwd='" + txt4pwd.Text + "'", con);
SqlDataReader reader = cmd.execute Reader();
Where login is the table and username and pwd are its fields. After this code all the values are stored in the reader object. I want to store username and pwd in the separate variables.
How can I accomplish this?
In general, when accessing your DB, you should be using something similar to this instead to eliminate SQL injection vulnerabilities:
using (SqlCommand myCommand = new SqlCommand("SELECT * FROM USERS WHERE USERNAME=#username AND PASSWORD=HASHBYTES('SHA1', #password)", myConnection))
{
myCommand.Parameters.AddWithValue("#username", user);
myCommand.Parameters.AddWithValue("#password", pass);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader())
...................
}
But more realistically to store credentials, you should be using something like the Membership system instead of rolling your own.
You're running a huge risk of sql injection with that. Use SQL Parameters for values into SqlCommands.
If you mean c# variables, and if you want to get them from db, just do this:
SqlDataReader reader = cmd.execute Reader();
if (reader.Read())
{
string username = reader["username"];
string pwd = reader["password"];
}
While you are at it, parameterize your query and prevent sql injection:
SqlCommand cmd = new Sqlcommand("select * from login where username=#username and pwd=#pwd", con);
cmd.Parameters.AddWithValue("#username", txt4name.Text);
cmd.Parameters.AddWithValue("#pwd", txt4pwd.Text);
Definitely heed the advice about SQL injection but here is the answer to your question:
String username;
String pwd;
int columnIndex = reader.GetOrdinal("username");
if (!dataReader.IsDBNull(columnIndex))
{
username = dataReader.GetString(columnIndex);
}
columnIndex = reader.GetOrdinal("pwd");
if (!dataReader.IsDBNull(columnIndex))
{
pwd = dataReader.GetString(columnIndex);
}
string userName = txt4name.Text;
string password = txt4pwd.Text;
Is that really what you want? Just to get that data into variables?
You really need to use parameterized SQL. There's an example here
Furthermore, your question doesn't really make sense; you want the username and password in seperate variables? they already are seperate in your example. If you are unable to assign them to strings I suggest following some tutorials.
Another approach is to load the reader results into a DataTable like so:
DataTable Result = new DataTable();
Result.Load(reader);
If your login table only contains two columns (userName and password) that are unique you end up with Result containing only one row with the information. You can then get the column values from each column:
string userName = Result.Rows[0].Field<string>("userName");
string password = Result.Rows[0].Field<string>("pwd");
private void but_login_Click(object sender, EventArgs e)
{
string cn = "Data Source=.;Initial Catalog=mvrdatabase;Integrated Security=True";
SqlConnection con = new SqlConnection(cn);
con.Open();
SqlCommand cmd = new SqlCommand("select count (*) from logintable where username ='" + txt_uname.Text + "'and password='" + txt_pass.Text + "'", con);
int i = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (i == 1)
{
Form2 f2 = new Form2();
MessageBox.Show("User login successfully........");
this.Hide();
f2.Show();
}
else
{
MessageBox.Show("INCORRECT USERID AND PASSWORD", "Error");
}
}
You can usually find basic usage examples on MSDN, like this one for SqlDataReader.

Categories