使用PBKDF2加盐哈希存储密码,推荐Rfc2898DeriveBytes类生成唯一盐值、高迭代次数的哈希,并与盐一起存储;ASP.NET Core Identity内置PasswordHasher更安全便捷,避免使用弱算法或自定义实现。

在.NET中安全地存储密码,核心是使用强哈希算法并加盐(salt),防止彩虹表攻击和暴力破解。直接存储明文密码是严重安全漏洞,必须避免。推荐使用内置的、经过验证的加密库来处理密码哈希,而不是自行实现算法。
.NET提供了Rfc2898DeriveBytes类,基于PBKDF2(Password-Based Key Derivation Function 2)标准,结合随机盐值和高迭代次数,能有效抵御暴力破解。
关键要点:
using System;
using System.Security.Cryptography;
using System.Text;
public class PasswordHasher
{
private const int SaltSize = 16;
private const int HashSize = 32;
private const int Iterations = 100000;
public static string HashPassword(string password)
{
using (var rng = RandomNumberGenerator.Create())
{
byte[] salt = new byte[SaltSize];
rng.GetBytes(salt);
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations, HashAlgorithmName.SHA256))
{
byte[] hash = pbkdf2.GetBytes(HashSize);
return Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash);
}
}
}
public static bool VerifyPassword(string password, string hashedPassword)
{
var parts = hashedPassword.Split(':');
if (parts.Length != 2) return false;
byte[] salt = Convert.FromBase64String(parts[0]);
byte[] expectedHash = Convert.FromBase64String(parts[1]);
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations, HashAlgorithmName.SHA256))
{
byte[] actualHash = pbkdf2.GetBytes(HashSize);
return CryptographicOperations.FixedTimeEquals(actualHash, expectedHash);
}
}
}
如果你使用ASP.NET Core Identity,它默认使用PasswordHasher<TUser>,基于PBKDF2实现,已配置安全参数,无需手动处理。
直接调用即可:
var hasher = new PasswordHasher<ApplicationUser>();
string hashed = hasher.HashPassword(user, "用户密码");
var result = hasher.VerifyPassword(user, hashed, "输入密码");
if (result == PasswordVerificationResult.Success)
{
// 登录成功
}
该方式更安全且维护成本低,适合大多数Web应用。
确保不犯以下典型错误:
PBKDF2目前仍安全,但内存硬性算法如Argon2或BCrypt更能抵抗GPU/ASIC攻击。.NET中可通过NuGet引入第三方库支持:
string hash = BCrypt.HashPassword("password", BCrypt.GenerateSalt(12));
bool isValid = BCrypt.Verify("password", hash);
基本上就这些。选择合适方案后,坚持统一使用,并定期审查安全策略。密码安全是系统防线的第一道门槛,不可轻视。">
以上就是.NET中如何安全地进行密码哈希存储_密码安全哈希存储方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号