我一直在一遍又一遍地阅读代码以查看错误发生在哪里,但我无法找到它。我已经从 stackoverflow 复制了这段代码,但从未真正检查过它或完全理解它以修复它。我正在从 web 服务接收密码、散列、加盐并将其保存到 SqlServer 2008。SqlServer 上的变量被声明为邮件为 nvarchar(64)、散列为 varbinary(128) 和盐为 varbinary(128)。密码正在保存,但是当我尝试检查密码是否正确时,该方法总是返回 false。这是我的方法。
public int InsertData(string mail,string Password)
{
int lineas;
UserData usuario = HashPassword(Password);
using (SqlConnection connection = new SqlConnection(Connection))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Usuarios (Mail,Hash,Salt) VALUES (@mail,@hash,@salt)";
command.Parameters.AddWithValue("@mail", mail);
command.Parameters.AddWithValue("@hash", usuario.Password);
command.Parameters.AddWithValue("@salt", usuario.salt);
connection.Open();
lineas=command.ExecuteNonQuery();
}
usuario = null;
return lineas;
}
private UserData HashPassword(string Password)
{
//This method hashes the user password and saves it into the object UserData
using (var deriveBytes = new Rfc2898DeriveBytes(Password, 20))
{
byte[] salt = deriveBytes.Salt;
byte[] key = deriveBytes.GetBytes(20); // derive a 20-byte key
UserData usuario = new UserData();
usuario.Password = key;
usuario.salt = salt;
return usuario;
}
}
下一个方法是我用来验证密码的方法,它总是返回 false
private bool CheckPassword(string Password, byte[] hash, byte[] salt)
{
// load salt and key from database
using (var deriveBytes = new Rfc2898DeriveBytes(Password, salt))
{
byte[] newKey = deriveBytes.GetBytes(20); // derive a 20-byte key
if (!newKey.SequenceEqual(hash))
return false;
else
return true;
}
}
此方法接收登录信息
public bool ValidateLogIn(string mail, string Password)
{
using (SqlConnection connection = new SqlConnection(Connection))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "Select * from Usuarios where Mail=@mail";
command.Parameters.AddWithValue("@mail",mail);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
reader.Read();
byte[] hash = (byte[])reader["Hash"];
byte[] salt = (byte[])reader["Salt"];
if(CheckPassword(Password,hash,salt))
{
/
UpdateData(mail, Password);
return true;
}
else
{
return false;
}
}
}
}
有什么想法可能是错的吗?
编辑:我找到了获得哈希码的链接 https://stackoverflow.com/a/4330586/1861617