Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I dispose of X509Certificate2?

I'm using IdentityServer4 and I want to load signing certificate from file. For example,

var certificate = new X509Certificate2(
        path, 
        password, 
        X509KeyStorageFlags.EphemeralKeySet);

services.AddIdentityServer()
        .AddSigningCredential(certificate)
...
certificate.Dispose();

The code above won't work when I request the token from IdentityServer. But it will work in case I remove certificate.Dispose();.

I also tried another option. I created RsaSecurityKey from certificate's private key and used it for adding signing credential. And in this case disposing will not break anything.

var rsk = new RsaSecurityKey(certificate.GetRSAPrivateKey()))

services.AddIdentityServer()
        .AddSigningCredential(rsk)
...
certificate.Dispose()

So my question is more general. Should I dispose X509Certificate2 object created from the existing certificate?


From Microsoft Docs:

Starting with the .NET Framework 4.6, this type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly.

like image 236
qwermike Avatar asked May 28 '19 07:05

qwermike


1 Answers

By looking at .NET Core source code, X509Certificate2 and its base class X509Certificate use class CertificatePal to deal with the certificate. The CertificatePal class supports creation of objects of the class from various sources: blob, file, certificate store. It calls Windows CryptoAPI to get a handle to the certificate when creating the object. So, after using the object, it would be necessary to free the resources pointed to by the handle. The good news is that, the handle is stored in a SafeCertContextHandle object, which is guaranteed to close the handle after garbage collector collects the X509Certificate2 object and finishes calling the finalizers of the objects. My understanding is that, we don't need to call the Dispose method manually.

like image 181
robbie fan Avatar answered Sep 23 '22 00:09

robbie fan