如何更新使用MD5加密的密码并存储到sql server 2005数据库中

时间:2012-04-20 16:57:01

标签: asp.net c#-4.0

我创建了一个用户帐户表。 Login中有两个字段,用于存储用户ID和密码,用于以加密格式存储密码。使用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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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