值得知道的KeyedHashAlgorithm.ComputeHash()是,这不是线程安全的,因为它给出了相同的不确定结果KeyedHashAlgorithm.Key。
在我的情况下,我想缓存 KeyedHashAlgorithm 因为我KeyedHashAlgorithm.Key的总是相同的,以从客户端验证真实性。我意识到这ComputeHash()并不一致,可能它会将内部变量缓存到KeyedHashAlgorithm实例中。我应该缓存每个线程的实例ThreadStatic或ThreadLocal. 这是测试:
静态KeyedHashAlgorithm给出不一致的结果:
var kha = KeyedHashAlgorithm.Create("HMACSHA256");
kha.Key = Encoding.UTF8.GetBytes("key");
Action comp = () =>
{
var computed = kha.ComputeHash(Encoding.UTF8.GetBytes("message"));
Console.WriteLine(Convert.ToBase64String(computed));
};
Parallel.Invoke(comp, comp, comp, comp, comp, comp, comp, comp);
与KeyedHashAlgorithm每个线程相比:
ThreadLocal<KeyedHashAlgorithm> tl= new ThreadLocal<KeyedHashAlgorithm>(() =>
{
var kha = KeyedHashAlgorithm.Create("HMACSHA256");
kha.Key = Encoding.UTF8.GetBytes("key");
return kha;
});
Action comp = () =>
{
var computed = tl.Value.ComputeHash(Encoding.UTF8.GetBytes("message"));
Console.WriteLine(Convert.ToBase64String(computed));
};
Parallel.Invoke(comp, comp, comp, comp, comp, comp, comp, comp);
此代码可用于测试“线程安全”结果的其他功能。希望这对其他人有帮助。