bcrypt的.Net实现,它实现了HashAlgorithm?

Ear*_*rlz 4 .net hash bcrypt password-hash bcrypt.net

我想在我的身份验证库中允许bcrypt支持.现在的问题之一是我认为哈希将是类型的HashAlgorithm.Bcrypt.net没有实现这个类.此外,它是密封的,所以我必须自己创建自己的分支并自己修改它.有没有更好的替代方案已经实现了HashAlgorithm?

Gal*_*llo 6

试试这个:

public class BCryptHasher : HashAlgorithm
{
    private MemoryStream passwordStream = null;

    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
        if (passwordStream == null || Salt == null)
            Initialize();

        passwordStream.Write(array, ibStart, cbSize);
    }

    protected override byte[] HashFinal()
    {
        passwordStream.Flush();

        // Get the hash
        return Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Encoding.UTF8.GetString(passwordStream.ToArray()), Salt));            
    }

    public override void Initialize()
    {
        passwordStream = new MemoryStream();

        // Set up salt
        if (Salt == null)
        {
            if (WorkFactor == 0)
                Salt = BCrypt.Net.BCrypt.GenerateSalt();
            else
                Salt = BCrypt.Net.BCrypt.GenerateSalt(WorkFactor);
        }
    }

    public int WorkFactor { get; set; }

    public string Salt { get; set; }

    public bool Verify(string plain, string hash)
    {
        return BCrypt.Net.BCrypt.Verify(plain, hash);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

BCryptHasher hasher = new BCryptHasher();
string pw = "abc";
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(Encoding.UTF8.GetBytes(pw)));
Run Code Online (Sandbox Code Playgroud)

此外,我添加了一个帮助程序验证方法,以便您可以验证密码和哈希匹配,但如果您只是调用默认的BCrypt.Verify,则可以消除此问题.

bool matches = hasher.Verify(pw, hash);
Run Code Online (Sandbox Code Playgroud)

我添加了一些额外的属性,因此您可以在执行哈希之前传入预先计算的salt或工作因子以生成新的salt:

string pw = "abc";
hasher.Salt = "$2a$06$If6bvum7DFjUnE9p2uDeDu";
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(Encoding.UTF8.GetBytes(pw)));
Run Code Online (Sandbox Code Playgroud)

我尝试使用BCrypt测试用例"abc"和"$ 2a $ 06 $ If6bvum7DFjUnE9p2uDeDu"并得到正确的哈希值.

  • 对于未来的观众:请注意,这与HashAlgorithm"传统上"不兼容.由于BCrypt如何工作,它有我称之为"跟踪盐".您不能只将盐添加到哈希密码或类似的东西,您必须以纯文本(或加密)的方式显式存储盐,以获得密码的相同哈希. (2认同)