Friday, April 20, 2012

How to update password encrypted using MD5 and stored into sql server 2005 database

I have created a user account table. There are two fields in it Login which stores user id and Password which stores password in encrypted format. The password is encrypted at the time of registration using MD5 hashing. If the user wants to change his password, how will he change it into the database. I tried to update the password using simple update statement, but it didnt work.



My code is:



//Code

public int Changep(string strLogin, string strPassword, string newpass)
{
//Create a connection
string cs = "data source=DELL-PC;initial catalog=project;user id=sa;password=pass";
SqlConnection objConn = new SqlConnection(cs);


// Create a command object for the query
string strSQL = "UPDATE tblLogins SET Password= @Password WHERE Login=@Username AND Password = @Password2";

SqlCommand objCmd = new SqlCommand(strSQL, objConn);

//Create parameters
SqlParameter paramUsername;
paramUsername = new SqlParameter("@Username", SqlDbType.VarChar, 25);
paramUsername.Value = strLogin;
objCmd.Parameters.Add(paramUsername);

//Encrypt the password
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedBytes;
UTF8Encoding encoder = new UTF8Encoding();
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPassword));
SqlParameter paramPwd;
paramPwd = new SqlParameter("@Password", SqlDbType.Binary, 16);
paramPwd.Value = hashedBytes;
objCmd.Parameters.Add(paramPwd);

//Encrypt the old password
MD5CryptoServiceProvider md5Hasher2 = new MD5CryptoServiceProvider();
byte[] hashedBytes2;
UTF8Encoding encoder2 = new UTF8Encoding();
hashedBytes2 = md5Hasher2.ComputeHash(encoder2.GetBytes(strPassword));
SqlParameter paramPwd2;
paramPwd2 = new SqlParameter("@Password2", SqlDbType.Binary, 16);
paramPwd2.Value = hashedBytes;
objCmd.Parameters.Add(paramPwd2);
int iResults;
//Insert the record into the database
try
{
objConn.Open();
//We use execute scalar, since we only need one cell
iResults = Convert.ToInt32(objCmd.ExecuteScalar().ToString());
if(iResults==1)
return PassUpdated;
else
return Updatefailed;
}
catch
{
return Updatefailed;
}
finally
{
objConn.Close();
}
}
}




No comments:

Post a Comment