What is the impact of the `PersistKeySet`-StorageFlag when importing a Certificate in C#

别来无恙 提交于 2019-11-30 20:08:40

When importing a PFX the public certificate element is loaded into memory, and the private key material is squirreled away into a key storage provider. The default behavior in .NET is to delete the private key material when the X509Certificate2 object is Disposed (or its resources are being Finalized via Garbage Collection). The PersistKeySet flag prevents this cleanup from happening.

If you're adding to a persisted certificate store, you always want to set PersistKeySet. When not adding to a persisted store you very likely do not want it set.

If your importing process is long-lived then the behavior you'd see is that at an arbitrary time after the import new accesses to the private key start failing. If it's short-lived then it probably always failed to work.

In my understanding, the PersistKeySet flag, if specified, it persists on disk the private key of the imported PFX at the same location from where certificate that was the source of the exported PFX (userkeyset or machinekeyset). If the PFX was generated by a tool (e.g. pvk2pfx.exe) then there is no source and default is used (userkeyset).

In this case, if the private key of certificate that was the source of the exported PFX was stored at machinekeyset, then the private key will be imported at machinekeyset, here: \ProgramData\Microsoft\Crypto\RSA\MachineKeys.

Otherwise, it will be stored at userkeyset, here: \Users\user\AppData\Roaming\Microsoft\Crypto\RSA\S-1-....

If you want your certificate to be available across the machine, disregarding the origin location of the PFX, you might want to consider using the MachineKeySet instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!