我希望在我的身份验证库中允许 bcrypt 支持。现在的问题之一是我假设 hasher 将是 type HashAlgorithm
。Bcrypt.net 没有实现这个类。此外,它是密封的,所以我必须自己制作分支并自己修改它。有没有更好的替代方案已经实现了 HashAlgorithm?
问问题
2014 次
1 回答
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);
我添加了一些额外的属性,因此您可以在进行哈希之前传入预先计算的盐或工作因子以生成新的盐:
string pw = "abc";
hasher.Salt = "$2a$06$If6bvum7DFjUnE9p2uDeDu";
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(Encoding.UTF8.GetBytes(pw)));
我用盐为“$2a$06$If6bvum7DFjUnE9p2uDeDu”的 BCrypt 测试用例“abc”进行了尝试,并得到了正确的哈希值。
于 2011-06-27T18:43:05.887 回答