c# - 使用 Pbkdf2 加密通过 Salt 加密和验证哈希密码

标签 c# encoding asp.net-core cryptography passwords

我使用以下代码创建哈希密码和盐:

// generate a 128-bit salt using a secure PRNG
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
    rng.GetBytes(salt);
}

// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
string hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2(
    password: password,
    salt: salt,
    prf: KeyDerivationPrf.HMACSHA1,
    iterationCount: 10000,
    numBytesRequested: 256 / 8));

我将 HashedPassword 和 Salt 存储在数据库中。

现在我想验证用户登录时的密码:

public bool VerifyPassword(string userEnteredPassword, string dbPasswordHash, string dbPasswordSalt)
{
    string hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2(
        password: userEnteredPassword,
        salt: Encoding.ASCII.GetBytes(dbPasswordSalt),
        prf: KeyDerivationPrf.HMACSHA1,
        iterationCount: 10000,
        numBytesRequested: 256 / 8));

    return dbPasswordHash == hashedPassword;
}

这不起作用,我得到的哈希密码与数据库中存储的密码完全不同。据我了解,您应该将盐添加到用户登录时输入的密码中,然后运行相同的哈希密码函数。上面不是等价的吗?

最佳答案

正如 Maarten Bodewes 提到的,ASCII 是问题所在。下面的代码返回 true。我所做的只是将 salt: Encoding.ASCII.GetBytes(dbPasswordSalt), 更改为 salt: System.Convert.FromBase64String(dbPasswordSalt),

public bool VerifyPassword(string userEnteredPassword, string dbPasswordHash, string dbPasswordSalt)
    {
        Console.WriteLine(dbPasswordSalt.ToString());
        Console.WriteLine(dbPasswordHash.ToString());

        string hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2(
            password: userEnteredPassword,
            salt: System.Convert.FromBase64String(dbPasswordSalt),///Encoding.ASCII.GetBytes(dbPasswordSalt),
            prf: KeyDerivationPrf.HMACSHA1,
            iterationCount: 10000,
            numBytesRequested: 256 / 8));
        Console.WriteLine(hashedPassword.ToString());
        return dbPasswordHash == hashedPassword;
    }

关于c# - 使用 Pbkdf2 加密通过 Salt 加密和验证哈希密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45220359/

相关文章:

c# - 如何在单个项目中使用 2 个不同的连接字符串?

JavaScript 编码无法正常工作

c# - WebDav Word 2016 checkin 按钮

c# - 在 ASP.NET Core 中实现 "JSON Merge Patch"- 区分 null 和未定义属性的最佳方法

c# - Sitecore 以编程方式添加布局。值不能为空。参数名称路径

c# - 如何用c#解压MSZIP文件?

python - 运行 Django 开发服务器时出现 UnicodeDecodeError

ruby-on-rails - mysql2 gem 0.3.15 提供编码设置为 "utf8"的 ASCII-8BIT

c# - 在 Asp.Net 5 中访问客户端 IP 地址 (REMOTE_ADDR)

c# - 将复杂类型的字典绑定(bind)到 RadioButtonList