在ASP.NET应用程序中,我使用md5将密码保存为数据库的“二进制”数据。使用md5以二进制形式保存和比较数据库密码
我该如何比较密码?
我用code in this article to encrypt the password with md5
的代码工作。当用户在登录时输入密码时,如何比较密码?检查密码是否与数据库中的加密密码相匹配的代码是什么?
我用下面的代码,但它总是显示“不正确的用户名或密码”,即使它是正确的。“该modifird代码”
Byte[] hashedBytes;
string Password = txtPassword.Text;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
UTF8Encoding encoder = new UTF8Encoding();
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Password));
Byte[] pass = new Byte[16];
SqlConnection conn = new SqlConnection("Data Source=Shihab-PC;Initial Catalog=test;User ID=sh;password=admin");
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE [email protected]", conn);
cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
pass = (Byte[])rdr["password"];
foreach (Byte b in pass)
{
Label1.Text += b.ToString() + " ";
//Response.Write(b.ToString());
string UserName = txtUserName.Text;
bool isMatch = false;
Byte[] password = new Byte[16];
SqlConnection con = new SqlConnection("Data Source=Shihab-PC;Initial Catalog=test;User ID=sh;password=admin");
con.Open();
SqlCommand cmdd = new SqlCommand(string.Format("select * from Users where UserName='{0}'", UserName), con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
SqlDataReader dr = cmdd.ExecuteReader();
if (dr.Read())
{
password = (Byte[])dr["Password"];
}
foreach (Byte c in password)
{
Label2.Text += c.ToString() + " ";//I didnt close the pracket fo that reason data is repeted if I close it I cant type c.toString
while (dr.Read())
{
if (b.ToString() == c.ToString()) // I mean this statment
{
isMatch = true;
}
}
}
dr.Close();
con.Close();
if (isMatch)
{
Response.Write("correct");
}
else
{
Response.Write("Incorrect username or password!");
}
}
编辑的代码 保护无效的button1_Click(对象发件人,EventArgs的) { } public static bool ValidateUser(string userName,string password) {SqlConnection con = new SqlConnection(“Data Source = shihab-PC; Initial Catalogue = test; User ID = sh; password = admin”); con.Open();
using (var connection = new SqlConnection("connectionString"))
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT dbo.checkUserExists (@userName, @password)";
command.Parameters.Add("@userName", SqlDbType.NVarChar, 25).Value = userName;
command.Parameters.Add("@password", SqlDbType.NVarChar).Value = GenerateHash(password);
connection.Open();
return (bool)command.ExecuteScalar();
}
}
private static string GenerateHash(string value)
{
return Convert.ToBase64String(new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes("salt")).ComputeHash(Encoding.UTF8.GetBytes(value)));
}
}
MD5不加密;没有办法解密,缺乏暴力或MD5的弱点。 MD5是一个散列;许多不同的输入可以产生相同的散列输出。 – 2010-11-11 18:44:28
还有一些事情:1)MD5坏了;使用SHA-1或(更好)SHA-2。 2)每行使用不同的盐。 – 2010-11-11 18:45:31
我不想解密,我只是想比较用户输入的密码和存储在数据库中的密码 – shihab 2010-11-11 20:15:15