我看到我维护的一些代码存在问题。下面的代码有一个private static SHA1
成员(这是一个IDisposable
,但因为它是static
,它永远不会被最终确定)。然而,在压力下这段代码抛出表明它已经关闭了异常:为什么SHA1.ComputeHash在高负载下有很多线程会失败?
Caught exception. Safe handle has been closed"
Stack trace: Call stack where exception was thrown
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
at System.Security.Cryptography.Utils.HashData(SafeHashHandle hHash, Byte[] data, Int32 cbData, Int32 ibStart, Int32 cbSize)
at System.Security.Cryptography.Utils.HashData(SafeHashHandle hHash, Byte[] data, Int32 ibStart, Int32 cbSize)
at System.Security.Cryptography.HashAlgorithm.ComputeHash(Byte[] buffer)
的代码中的问题是:
internal class TokenCache
{
private static SHA1 _sha1 = SHA1.Create();
private string ComputeHash(string password)
{
byte[] passwordBytes = UTF8Encoding.UTF8.GetBytes(password);
return UTF8Encoding.UTF8.GetString(_sha1.ComputeHash(passwordBytes));
}
我的问题是明显,是什么引发了这个问题。对SHA1.Create
的调用是否可以无提示失败(有多少加密资源可用)?这可能是由应用程序域名下降造成的吗?
其他理论?
这是什么都与处置呢?另外,哪个“SHA1”类是那个? – 2014-10-27 16:51:27
你确定类SHA1是线程安全吗?当它失败时你能够获取被哈希处理的密码吗? – Rob 2014-10-27 16:51:56
@约翰桑德斯,对不起,你是对的。这与Dispose无关。我认为System.Security.Cryptography.SHA1CryptoServiceProvider上的终结器可能以某种方式被触发。 http://msdn.microsoft.com/en-us/library/e7hyyd4e(v=vs.110).aspx – MvdD 2014-10-27 16:53:50