I have a class that is used to encrypt textual data. I am trying to reuse the ICryptoTransform objects where possible. However, the second time I am trying to use the same o
What you're missing is the bug (and bugfix) in .NET Framework :).
There's a Microsoft Connect Issue about this same problem; specifically that AesCryptoServiceProvider.CreateDecryptor() returns an object that says CanReuseTransform=true
, but doesn't seem to behave correctly.
The bug was fixed in the .NET 4.6.2 release, but is guarded behind a retargeting change. That means that in order to see the fix you need to
If you have the newer framework installed, but want to keep your executable targeting a lower version of the framework you need to set the switch Switch.System.Security.Cryptography.AesCryptoServiceProvider.DontCorrectlyResetDecryptor
to false
.
From the AppContext class documentation (under "Remarks"):
Once you define and document the switch, callers can use it by using the registry, by adding an AppContextSwitchOverrides element to their application configuration file, or by calling the AppContext.SetSwitch(String, Boolean) method programmatically.
For the configuration file (your.exe.config):