-4

我创建了一个用户帐户表。其中有两个字段 Login 存储用户 ID 和 Password 以加密格式存储密码。密码在注册时使用 MD5 散列加密。如果用户想更改他的密码,他将如何将其更改到数据库中。我尝试使用简单的更新语句更新密码,但没有成功。

我的代码是:

//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();
        }
    }
}
4

1 回答 1

0

您正在哈希strPassword旧密码和新密码。我认为您需要提示输入旧密码和新密码,然后将旧密码散列到您的WHERE子句中。

于 2012-04-20T17:08:58.560 回答