[Breaking change]: Windows Private Key Lifetime Simplified in .NET 9 #42613
Labels
breaking-change
Indicates a .NET Core breaking change
doc-idea
Indicates issues that are suggestions for new topics [org][type][category]
in-pr
This issue will be closed (fixed) by an active pull request.
Pri1
High priority, do before Pri2 and Pri3
📌 seQUESTered
Identifies that an issue has been imported into Quest.
Description
When loading a PKCS#12/PFX on Windows without specifying either the
PersistKeySet
orEphemeralKeySet
storage options, .NET determines when a private key is no longer needed and should be erased. In prior versions of .NET (and in .NET Framework) two different sets of logic were utilized. In .NET 9 this has been simplified to one.Version
.NET 9 Preview 7
Previous behavior
When loading a certificate (and its private key) from a PKCS#12/PFX with
new X509Certificate2(pfx, password, flags)
, the loaded certificate represented the lifetime of the private key. When this certificate object was disposed (or finalized if it was garbage collected without being disposed) the associated private key would be deleted. No shared ownership or transfer of ownership occurred.When loading a certificate (and its private key) from a PKCS#12/PFX with
X509Certificate2Collection.Import(pfx, password, flags)
each loaded certificate that had a private key would track the lifetime, as with the single certificate load. But, in addition, a marker was placed on the native copy of the certificate to indicate that any copies should also track the private key lifetime. If a secondX509Certificate2
object was created in terms of the same underlyingPCERT_CONTEXT
value, then whichever copy was disposed (or finalized) first would erase the private key out from under the other.New behavior
Starting in .NET 9, the lifetime is always associated with the X509Certificate2 instance that was directly produced from the PKCS#12/PFX load.
In previous versions, this code will fail (either with a CryptographicException, or a NullReferenceException) because the private key was deleted. In .NET 9 it will succeed.
Type of breaking change
Reason for change
Most workloads loading a PKCS#12/PFX use the single certificate load, and understand the lifetime mechanics associated with that method. The mechanics associated with the collection load were often surprising, and could lead to premature key erasure.
Recommended action
Users who understood the collection-load lifetime management and were depending on calling
Dispose
on a clone to cause key erasure should ensure that they are also (or instead) calling Dispose on the original loaded object.Feature area
Cryptography
Affected APIs
Associated WorkItem - 320278
The text was updated successfully, but these errors were encountered: