Comparing two rows in the same table in sql server - c#

I have looked at similar answers but, this is what I am looking for since I did not find any answers from previously answered questions:
This is my scenario: I have a table [res_user] with username, password, key_pin which saves a username, an encrypted password, and a 4 digit pin or key.
I am making an app in C# that allows a manager to log in and make changes to the database from the app itself.
The manager is first prompted to log in with a username, a password, and their key_pin they are provided with. The pin is what will encrypt and decrypt the password to and from the database.
Now I have a username [manager] and an encrypted password already saved in the database with the key_pin.
How can I make sure that the manager logging in is the right one, meaning how can I compare the username and the encrypted password in the database from the C# app.
These are the steps that I though of that I will implement in the app itself (using SQL syntax in c#):
Encrypt the password,
Get the saved encryption in the database using the login username, and
Compare the encryption returning a yes or a no back to the app for access control.
allowing 5 attempts to log in.
This is the first and second part I did:
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["STRING"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.Res_User", con))
{
cmd.CommandText = "INSERT INTO Res_User(username, password, key_pin) SELECT '" + username + "' , dbo.fnEncDecRc4('" + pin + "','" + password + "'), '" + pin + "'";
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added", "Information", MessageBoxButtons.OK);
cmd.CommandText = "SELECT password FROM Res_User WHERE username = #username";
cmd.Parameters.AddWithValue("#username", username);
cmd.ExecuteNonQuery();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
MessageBox.Show(reader["password"].ToString(), "Information", MessageBoxButtons.OK);
}
}
}
How do I go about doing the third part?
Only if someone can help me compare the saved enc. password and the login enc. password which I did in part one.
Let me know if more information is needed.
Thank You.
Any help will be appreciated.

You could try re-encrypting the password and pin on the server when you're doing validation on the server. So that you will call your encrypt function, then do a comparison and if you have results, you know that the correct password was entered. Modifying your code, it would look like:
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["STRING"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.Res_User", con))
{
cmd.CommandText = "INSERT INTO Res_User(username, password, key_pin) SELECT '" + username + "' , dbo.fnEncDecRc4('" + pin + "','" + password + "'), '" + pin + "'";
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added", "Information", MessageBoxButtons.OK);
cmd.CommandText = "SELECT password FROM Res_User WHERE username = #username AND key_pin = #pin AND password = dbo.fnEncDecRc4(#pin, #password)";
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#pin", pin);
cmd.Parameters.AddWithValue("#password", password);
cmd.ExecuteNonQuery();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
//successfully validated.
}
}

Related

I'm trying to encrypt my data on a password management software

For example , this is my add user code , i want encrypt those data with the aes 256 algorithm , I want to encrypt the data that I want to store in my database , I'm using an insert command , i want the data to be crypted when it's stored on the database , i want to be able to recover those data thus decrypt them , i believe i will need a user provided key to do so , i want the data to be decrypted only from the client side, i hope it's clear, I tried the documentation but i find it hard to understand as i'm still a begginer in c# , please be very specific with your answers, i need details and code.
thank you
String firstname = textBox1.Text;
String fullname = firstname + " " + textBox2.Text;
string hh = Convert.ToString(DateTime.Now.Ticks.ToString().Substring(15));
string AccessKey = "";
while (AccessKey.Length != 3 || AccessKey.Substring(0, 1) == "0")
AccessKey = Convert.ToString(DateTime.Now.Ticks.ToString().Substring(15));
username = firstname +" "+ AccessKey;
String password = textBox3.Text;
String today = DateTime.Today.ToString("dd-MM-yyyy");
string oradb = "Data Source=CBSUAT;User Id=ramadan;Password=Raam20##;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into USER_MASTER (userid, fullname, username, password ) values (master_seq.nextval, '" + fullname + "' , '" + username + "', '" + password + "') ";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Your User Account has been create successfully , your username is : " + username + "");
conn.Dispose();

Invalid column name SQL

I have wasted hours trying to find what's incorrect in my code. Before adding a new column in the table, it was ok but after that, whenever I submit my form, it gives me an error
The column name is not valid. [ Node name (if any) = ,Column name = userID ]
Here is my code:
con.Open();
string query = "INSERT INTO PlayerTable
(username ,password, picture, scoreL1, scoreL2, scoreL3, userID)
VALUES
('" + #userName + "','" + #password + "',#picture," + #score1
+ "," + #score2 + "," + #score3 + "," + #num + ")";
cmd.Parameters.AddWithValue("#picture", a);
cmd.Parameters.AddWithValue("#username", userName);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#scoreL1", score1);
cmd.Parameters.AddWithValue("#scoreL2", score2);
cmd.Parameters.AddWithValue("#scoreL3", score3);
cmd.Parameters.AddWithValue("#userID", num);
cmd = new SqlCeCommand(query, con);
cmd.ExecuteNonQuery();
Shouldn't it be:
string query =
"INSERT INTO PlayerTable
(username, password, picture, scoreL1, scoreL2, scoreL3, userID)
VALUES(#userName, #password, #picture, #scoreL1, #scoreL2, #scoreL3, #userID)";
That is not #score1 but #scoreL1 and same for the others.
Edit
When you instantiate a new SqlCeCommand:
cmd = new SqlCeCommand(query, con);
you essentially erase the paramaters you set earlier.
Move the instantiation above the parameter assignments:
cmd = new SqlCeCommand(query, con);
cmd.Parameters.AddWithValue("#picture", a);
cmd.Parameters.AddWithValue("#username", userName);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#scoreL1", score1);
cmd.Parameters.AddWithValue("#scoreL2", score2);
cmd.Parameters.AddWithValue("#scoreL3", score3);
cmd.Parameters.AddWithValue("#userID", num);
cmd.ExecuteNonQuery();
You should not be surrounding your query parameters with quotes:
string query = "INSERT INTO PlayerTable
(username ,password, picture, scoreL1, scoreL2, scoreL3, userID)
VALUES(#userName, #password, #picture, #scoreL1, #scoreL2, #scoreL3, #userID )";
Additionally, you need to make sure your Parameter Names match the # values.

Database insert error: "string or binary data would be truncated"

When I log in, I am storing my username in the session. My requirement is that I want to store my username in my database. Here I am storing it in username1. When the username is entered, I can print it using response.write() and it is printing perfectly. However, when I am storing it in the database it is producing this error:
**sqlException was unhandled by user code
and exception at cmd.ExecuteScalar();
String or binary data would be truncated.
The statement has been terminated.**
Following is my ado.net code:
using (SqlConnection con =
new SqlConnection("Data Source=.;database=testdb1;Integrated Security=SSPI")) {
con.Open();
// SqlCommand cmd = new SqlCommand("delete from fileinfo where ID=" + Convert.ToInt32(Request.Params["one"]), con);
string uname = (string) Session["fname"].ToString() + " " + Session["lname"].ToString(); //Session["fname"].ToString()+" "+Session["lname"].ToString();
// Response.Write(uname);
// uname = "sri hari";
uname = uname + " ";
string uname1 = uname;
uname = uname.Trim();
SqlCommand cmd = new SqlCommand("insert into qry_details values('" + txt_query_name.Text + "','pending for approval','" + txt_query_description.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + qry + "','" + uname1 + "')", con);
cmd.ExecuteScalar();
}
check the length of qry_details table and see if its smaller than the string you send to the db?
basically the exception says you are trying to something bigger than the column length.
I would recommend you using a parametrized query. Your code is now vulnerable to SQL injection. Also you should use the ExecuteNonQuery method on the SQL command instead of ExecuteScalar when inserting values to the database:
var connectionString = "Data Source=.;database=testdb1;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "INSERT INTO qry_details VALUES (#query_name, 'pending for approval', #query_description, #date, #qry, #username)";
cmd.Parameters.AddWithValue("#query_name", txt_query_name.Text);
cmd.Parameters.AddWithValue("#query_description", txt_query_description.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#qry", qry);
cmd.Parameters.AddWithValue("#username", uname1);
cmd.ExecuteNonQuery();
}
This error mostly happen when the inserting value is larger than the field width defined in table on SQL Server.
Check if you are inserting date and time using DateTime.Now c# fuction, your Table must be of type DateTime. not Date or Time only.

Login page - Checking the database

I am trying to make a simple login page, user enters ID and password, and chooses role from a dropdown list:Student, Administrator or Instructor. Here is the code:
protected void loginButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=University;Integrated Security=True;Pooling=False";
//myConn.Open();
//string strqry = "Insert into students values (" + TextBox1.Text +
//",'" + TextBox2.Text + "','" + TextBox3.Text + "')";
//SqlCommand myCom = new SqlCommand(strqry, myConn);
//int numrow = myCom.ExecuteNonQuery();
//myConn.Close();
Int32 verify;
string query1 = "Select count(*) from Login where ID='" + idBox.Text + "' and Password='" + passwordBox.Text + "' and Type='"+ LoginAs.Text +"'" ;
SqlCommand cmd1 = new SqlCommand(query1, con);
con.Open();
verify = Convert.ToInt32(cmd1.ExecuteScalar());
con.Close();
if (verify > 0)
{
Response.Redirect("succesful.aspx");
}
else
{
Response.Redirect("unsuccesful.aspx",true);
}
}
The problem is, when i try without checking the value of the dropdown list called "LoginAs", it works fine and makes validation. But when i also check the Type, which is either Student, Administrator or Instructor it always makes unsuccesful login even though all the information is correct. Can anyone help me to find what is wrong?
Thanks
use parametrized queries maybe it will be resolved and you would prevent risks it goes like this
cmd1.Parameters.AddWithValue("#ID", idBox.Text);
The first points to check is the:
The all of the letters should has the same case.
The role should be truncated in database and in the application
But, it's preffered to use enum/int to define role of user instead of a text name.
Give a try to SqlDataReader class. You can catch if an reads occur.
Here is the link. While this not the case I recommend you to use a scalar function in your database or use EntityFramework or other ORM tools.

Sql error in asp.net c#

If you please help me out i have an error in my code that i can not understand it.
the error is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'Login'.
and my code:
public static void ChangePassword(string login, string password)
{
var sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query = #"update Organizer set Password ="+ password + "where Login=" + login + "";
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.CommandType = CommandType.Text;
try
{
sqlCon.Open();
cmd.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception ee) { throw ee; }
}
We've seen enough sql injection attacks, we don't need another one, please fix your code and use parameters.
Use using blocks to avoid leaking connections.
Install an exception handler like ELMAH.
Don't save passwords in the database
using (var sqlCon = new SqlConnection(...))
{
string query = #"update Organizer set Password =#password where Login=#login";
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 8000);
cmd.Parameters["#password"].Value = password;
cmd.Parameters.Add("#login", SqlDbType.VarChar, 8000);
cmd.Parameters["#login"].Value = login;
sqlCon.Open();
cmd.ExecuteNonQuery();
sqlCon.Close();
}
Try
string query = #"update Organizer set Password ='"+ password + "' where Login= '" + login + "'";
You are missing the ' around string, that being said you are likely very open to sql injection attacks ( Im guessing because of the code, and lack of a clearing function).
Also make sure your not storing passwords in plain text :)
The ' is used like " in sql.
If you were going to use the code above, your issue is that you're not wrapping the new password or login in single quotes:
string query =
#"update Organizer set Password = '" +
password +
"' where Login= '" + login + "'";
But I wouldn't use that code at all. It's quite dangerous since it allows people to pass in arbitrary SQL. I would use parameterized queries instead:
var query = "update organizer set password = #password where login = #login";
var command = new SqlCommand(query, sqlCon);
command.Parameters.Add("#password", SqlDbType.VarChar, 100, password);
command.Parameters.Add("#login", SqlDbType.VarChar, 100, login);
You need single quotes...
set Password = ' /*<---*/ "+ password + "' /*<---*/ where Login=' /*<---*/ " + login + "' /*<---*/ "

Categories

Resources