我正在尝试创建一个简单的asp.net网站,允许用户注册和登录。我已经成功地设法将所有数据存储在数据库中,并以登录表单对用户进行身份验证。但是,我现在要做的是每当一个新用户注册以MD5格式将密码存储在数据库中并匹配哈希以便用户能够登录时。
这是将用户存储在数据库中的register部分中的代码:
try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AssignmentDBConnectionString"].ConnectionString); conn.Open(); string insertQuery = "insert into [AsTable] ([Username],Email,Password) values (@Username ,@Email, @Password)"; SqlCommand com = new SqlCommand(insertQuery, conn); com.Parameters.AddWithValue("@Username", TextBoxUsername.Text); com.Parameters.AddWithValue("@email", TextBoxEmail.Text); com.Parameters.AddWithValue("@password", TextBoxPass.Text); com.ExecuteNonQuery(); Response.Redirect("Manager.aspx"); Response.Write("Registration Completed"); conn.Close(); } catch (Exception ex) { Response.Write("Error:"+ex.ToString()); }
这是登录部分中的代码,该代码对用户进行身份验证以使其登录:
conn.Open(); string checkPasswordQuery = "select Password from [AsTable] where Username ='" + TextBoxUsername.Text + "'"; SqlCommand passcom = new SqlCommand(checkPasswordQuery, conn); string password = passcom.ExecuteScalar().ToString().Replace(" ",""); if (password == TextBoxPassword.Text) { Session["New"] = TextBoxUsername.Text; Response.Write("Password is correct"); Response.Redirect("Index.aspx"); } else { Response.Write("Password is not correct"); } } else { Response.Write("Username is not correct"); } }
有什么想法要改变吗?
这就是我处理加密的方式
首先,我创建了一种将简单字符串转换为sha256的方法(我认为这比md5更好)
public string ToSHA256(string value) { SHA256 sha256 = SHA256.Create(); byte[] hashData = sha256.ComputeHash(Encoding.Default.GetBytes(value)); StringBuilder returnValue = new StringBuilder(); for (int i = 0; i < hashData.Length; i++) { returnValue.Append(hashData[i].ToString()); } return returnValue.ToString(); }
然后
只需在创建用户时更改代码即可
try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AssignmentDBConnectionString"].ConnectionString); conn.Open(); string insertQuery = "insert into [AsTable] ([Username],Email,Password) values (@Username ,@Email, @Password)"; SqlCommand com = new SqlCommand(insertQuery, conn); com.Parameters.AddWithValue("@Username", TextBoxUsername.Text); com.Parameters.AddWithValue("@email", TextBoxEmail.Text); com.Parameters.AddWithValue("@password", ToSHA256(TextBoxPass.Text)); com.ExecuteNonQuery(); Response.Redirect("Manager.aspx"); Response.Write("Registration Completed"); conn.Close(); } catch (Exception ex) { Response.Write("Error:"+ex.ToString()); }
然后在找回密码
conn.Open(); string checkPasswordQuery = "select Password from [AsTable] where Username ='" + ToSHA256(TextBoxUsername.Text) + "'"; SqlCommand passcom = new SqlCommand(checkPasswordQuery, conn); //string password = passcom.ExecuteScalar().ToString().Replace(" ",""); if (password == ToSHA256(TextBoxPassword.Text)) { Session["New"] = TextBoxUsername.Text; Response.Write("Password is correct"); Response.Redirect("Index.aspx"); } else { Response.Write("Password is not correct"); } } else { Response.Write("Username is not correct"); } }