diff --git a/src/libraries/Common/src/Internal/Cryptography/HashProviderCng.cs b/src/libraries/Common/src/Internal/Cryptography/HashProviderCng.cs index 3b864790b2525..c905ca1bd6996 100644 --- a/src/libraries/Common/src/Internal/Cryptography/HashProviderCng.cs +++ b/src/libraries/Common/src/Internal/Cryptography/HashProviderCng.cs @@ -127,10 +127,15 @@ public override void Reset() { if (_reusable && !_running) return; + DestroyHash(); + BCryptCreateHashFlags flags = _reusable ? + BCryptCreateHashFlags.BCRYPT_HASH_REUSABLE_FLAG : + BCryptCreateHashFlags.None; + SafeBCryptHashHandle hHash; - NTSTATUS ntStatus = Interop.BCrypt.BCryptCreateHash(_hAlgorithm, out hHash, IntPtr.Zero, 0, _key, _key == null ? 0 : _key.Length, BCryptCreateHashFlags.None); + NTSTATUS ntStatus = Interop.BCrypt.BCryptCreateHash(_hAlgorithm, out hHash, IntPtr.Zero, 0, _key, _key == null ? 0 : _key.Length, flags); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw Interop.BCrypt.CreateCryptographicException(ntStatus); diff --git a/src/libraries/System.Security.Cryptography.Algorithms/tests/HashAlgorithmTest.cs b/src/libraries/System.Security.Cryptography.Algorithms/tests/HashAlgorithmTest.cs index dc5738441db56..38f5704058996 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/tests/HashAlgorithmTest.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/tests/HashAlgorithmTest.cs @@ -488,6 +488,30 @@ public void Initialize_TransformBlock_Unused() } } + [Fact] + public void Initialize_DoubleInitialize_Works() + { + byte[] hashInput = new byte[] { 1, 2, 3, 4, 5 }; + byte[] expectedDigest; + + using (HashAlgorithm hash = Create()) + { + expectedDigest = hash.ComputeHash(hashInput); + } + + using (HashAlgorithm hash = Create()) + { + byte[] buffer = new byte[1024]; + hash.TransformBlock(buffer, 0, buffer.Length, buffer, 0); + hash.Initialize(); + hash.TransformFinalBlock(Array.Empty(), 0, 0); + hash.Initialize(); + hash.TransformFinalBlock(hashInput, 0, hashInput.Length); + + Assert.Equal(expectedDigest, hash.Hash); + } + } + protected class DataRepeatingStream : Stream { private int _remaining;