我希望在我的身份验证库中允许bcrypt支持。现在的问题之一是,我假设hasher的类型是HashAlgorithm。Bcrypt.net不实现此类。此外,它是密封的,所以我必须在它的基础上创建自己的分支,并自己修改它。有没有更好的替代方案已经实现了HashAlgorithm?
发布于 2011-06-28 02:43:06
试试这个:
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”尝试了一下,得到了正确的散列。
https://stackoverflow.com/questions/5643187
复制相似问题