【发布时间】:2020-03-12 20:30:31
【问题描述】:
我正在创建一个网站,该网站的 SQL 数据库连接到网站中的注册和登录功能。我想在将密码发送到数据库之前对密码进行哈希处理,我已经成功完成了,但是我发现当用户尝试登录时很难将哈希密码解密回来。
这是我的用户登录页面,我想在其中合并以下代码...
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DogWalkingSite
{
public partial class userlogin : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(strcon);
//checking to see if the connection is closed
if (con.State == System.Data.ConnectionState.Closed)
{
//opens state to connect to database
con.Open();
}
SqlCommand cmd = new SqlCommand("select * from user_master_tbl where user_id= '"+TextBox1.Text.Trim()+ "' and password= '" + TextBox2.Text.Trim() + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
//HasRows will become false if the inputs are false
if (dr.HasRows)
{
while (dr.Read())
{
Response.Write("<script>" + "alert('"+dr.GetValue(5).ToString()+"');" + "</script>");
//sessions used to determine when to show buttons
Session["username"] = dr.GetValue(5).ToString();
Session["name"] = dr.GetValue(0).ToString();
Session["role"] = "user";
}
Response.Redirect("homepage.aspx");
}
else
{
Response.Write("<script>" + "alert('Username does not exist');" + "</script>");
}
}
catch (Exception ex)
{
}
}
}
} ```
``` public static bool VerifyPassword(string username,
string password,AccountDataContext context)
{
var user = context.UserAccounts.FirstOrDefault(p => p.UserName == username);
if (user != null)
{
string salt = user.Password.Substring(user.Password.Length - DefaultSaltSize);
string hashedPassword = CreateHash(password, salt);
return hashedPassword.Equals(user.Password);
}
return false;
} ```
【问题讨论】:
-
“将散列密码翻译回原始密码” - 你没有。为简单起见,您直接比较散列,而不是解密散列来比较原始值(这是不可能的。它是 散列)。
-
散列密码的全部意义在于您无法从散列中反转实际密码。是的,两个不同的密码会产生相同的哈希值。
-
您需要存储散列密码
-
除了上述的 cmets 之外,也许还要重新审视你的腌制方法。盐应该是随机的
-
您应该将 HASH(pwd) 存储在您的数据库中,正如我从您的问题中所理解的那样,您已经这样做了,然后您应该将 row["passwordColumn"] 与 HASH(suppliedPassword) 进行比较以检查是否输入的密码与注册时(或上次更改密码时)设置的密码一致。盐在这里不能是随机的,因为通常盐是这样使用的:HASH(pwd + SALT)。如果您使用随机盐,您还应该将其存储在数据库中,以便在比较期间能够使用相同的值进行盐,例如: if(HASH(suppliedPassword + row["SALT"]) == row["passwordColumn]) { // 授予条目 }