在 asp.net 核心PasswordHasher类型中,VerifyHashedPassword 方法上有备注
/// <remarks>Implementations of this method should be time consistent.</remarks>
然后为了比较散列,它使用故意不优化和编写的代码,不要在循环中提前退出。
// Compares two byte arrays for equality. The method is specifically written so that the loop is not optimized.
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static bool ByteArraysEqual(byte[] a, byte[] b)
{
if (a == null && b == null)
{
return true;
}
if (a == null || b == null || a.Length != b.Length)
{
return false;
}
var areSame = true;
for (var i = 0; i < a.Length; i++)
{
areSame &= (a[i] == b[i]);
}
return areSame;
}
起初我认为没有这个时间可以用来确定散列有多接近,如果需要更长的时间,那么更多的散列是相同的。
然而,这没有任何意义,因为此时哈希已经经历了 1000 次 SHA256 迭代。因此,密码的任何更改都会产生完全不同的哈希值,并且知道您的密码产生几乎正确的哈希值并不能帮助您找到正确的哈希值。
确保恒定时间哈希验证的目的是什么?