我希望在我的身份验证库中允许bcrypt支持。现在的问题之一是我假设hasher将是HashAlgorithm
类型。 Bcrypt.net没有实现这个类。此外,它是密封的,所以我必须自己创建自己的分支并自己修改它。有没有更好的替代方案已经实现了HashAlgorithm?
答案 0 :(得分: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);
}
}
用法:
BCryptHasher hasher = new BCryptHasher();
string pw = "abc";
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(Encoding.UTF8.GetBytes(pw)));
此外,我添加了一个帮助程序验证方法,以便您可以验证密码和哈希匹配,但如果您只是调用默认的BCrypt.Verify,则可以消除此问题。
bool matches = hasher.Verify(pw, hash);
我添加了一些额外的属性,因此您可以在执行哈希之前传入预先计算的salt或工作因子来生成新的盐:
string pw = "abc";
hasher.Salt = "$2a$06$If6bvum7DFjUnE9p2uDeDu";
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(Encoding.UTF8.GetBytes(pw)));
我尝试使用BCrypt测试用例“abc”加上“$ 2a $ 06 $ If6bvum7DFjUnE9p2uDeDu”并获得正确的哈希值。