客户端应该将明文密码哈希化并将哈希密码发送到服务器进行验证。以下是一个示例:
using System.Security.Cryptography;
using System.Text;
public static string HashPassword(string password)
{
byte[] salt;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
byte[] hashBytes = new byte[36];
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);
return Convert.ToBase64String(hashBytes);
}
public static bool VerifyPassword(string savedPasswordHash, string password)
{
byte[] hashBytes = Convert.FromBase64String(savedPasswordHash);
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
for (int i = 0; i < 20; i++)
if (hashBytes[i + 16] != hash[i])
return false;
return true;
}
在登录时,客户端代码应将密码用以上函数哈希化,将哈希密码发送到服务器进行验证。