简体   繁体   English

我应该处理 X509Certificate2 吗?

[英]Should I dispose of X509Certificate2?

I'm using IdentityServer4 and I want to load signing certificate from file.我正在使用 IdentityServer4,我想从文件加载签名证书。 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.当我从 IdentityServer 请求令牌时,上面的代码将不起作用。 But it will work in case I remove certificate.Dispose();但它会在我删除certificate.Dispose();情况下工作certificate.Dispose(); . .

I also tried another option.我也尝试了另一种选择。 I created RsaSecurityKey from certificate's private key and used it for adding signing credential.我从证书的私钥创建了RsaSecurityKey并将其用于添加签名凭据。 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?我应该处理从现有证书创建的X509Certificate2对象吗?


From Microsoft Docs :来自微软文档

Starting with the .NET Framework 4.6, this type implements the IDisposable interface.从 .NET Framework 4.6 开始,此类型实现 IDisposable 接口。 When you have finished using the type, you should dispose of it either directly or indirectly.使用完类型后,应直接或间接处理它。

By looking at .NET Core source code, X509Certificate2 and its base class X509Certificate use class CertificatePal to deal with the certificate.通过查看.NET Core源代码, X509Certificate2及其基类X509Certificate使用CertificatePal类来处理证书。 The CertificatePal class supports creation of objects of the class from various sources: blob, file, certificate store. CertificatePal类支持从各种来源创建类的对象:blob、文件、证书存储。 It calls Windows CryptoAPI to get a handle to the certificate when creating the object.它在创建对象时调用 Windows CryptoAPI 来获取证书的句柄。 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.好消息是,句柄存储在一个SafeCertContextHandle对象中,保证垃圾收集器收集到X509Certificate2对象并调用完对象的终结器后关闭句柄。 My understanding is that, we don't need to call the Dispose method manually.我的理解是,我们不需要手动调用Dispose方法。

不,您不应该在应用程序运行时释放证书对象,因为当被请求时,IdentityServer 将尝试使用已释放的证书对象并且会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM