Why does SHA1.ComputeHash fail under high load with many threads?

后端 未结 1 1791
悲哀的现实
悲哀的现实 2020-12-16 00:25

I\'m seeing an issue with some code I maintain. The code below has a private static SHA1 member (which is an IDisposable but since it\'s stat

相关标签:
1条回答
  • 2020-12-16 01:18

    As per the documentation for the HashAlgorithm base class

    Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

    You should not share these classes between threads where different threads try and call ComputeHash on the same instance at the same time.

    EDIT This is what is causing your error. The stress test below yields a variety of errors due to multiple threads calling ComputeHash on the same hash algorithm instance. Your error is one of them.

    Specifically, I have seen the following errors with this stress test:

    • System.Security.Cryptography.CryptographicException: Hash not valid for use in specified state.
    • System.ObjectDisposedException: Safe handle has been closed

    Stress test code sample:

    const int threadCount = 2;
    var sha1 = SHA1.Create();
    var b = new Barrier(threadCount);
    Action start = () => {
                        b.SignalAndWait();
                        for (int i = 0; i < 10000; i++)
                        {
                            var pwd = Guid.NewGuid().ToString();
                            var bytes = Encoding.UTF8.GetBytes(pwd);
                            sha1.ComputeHash(bytes);
                        }
                    };
    var threads = Enumerable.Range(0, threadCount)
                            .Select(_ => new ThreadStart(start))
                            .Select(x => new Thread(x))
                            .ToList();
    foreach (var t in threads) t.Start();
    foreach (var t in threads) t.Join();
    
    0 讨论(0)
提交回复
热议问题