Search code examples
c#sslcertificatex509certificatex509certificate2

Prevent file creation when X509Certificate2 is created?


We create a X509Certificate2 object in our ASP.NET app to make periodic outgoing connections. Every time one of these certificates is created a new file is created in:

C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys

That folder now has 4 million files that never get cleaned up. I've tried removing the Persist flag

new X509Certificate2(certBytes, p12Pwd, X509KeyStorageFlags.MachineKeySet);

//no X509KeyStorageFlags.PersistKeySet

but that doesn't help -- still get the 2Kb file on every call.

I got my hopes up when I saw this answer, but this is a 2008 R2 server, and the temp files are not 0 bytes, so it seems to be a different case.

How can we use a X509Certificate2 without filling up the disk?


Solution

  • Use .NET 4.6:

    X509Certificate2 implements the IDisposable interface starting with the .NET Framework 4.6; in previous versions of the .NET Framework, the X509Certificate2 class does not implement this interface, and therefore the Dispose method does not exist.