gpt4 book ai didi

c# - 我应该处理 X509Certificate2 吗?

转载 作者:行者123 更新时间:2023-11-30 21:28:35 24 4
gpt4 key购买 nike

我正在使用 IdentityServer4,我想从文件中加载签名证书。例如,

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

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

当我从 IdentityServer 请求 token 时,上面的代码将不起作用。但它会在我删除 certificate.Dispose(); 的情况下工作。

我还尝试了另一种选择。我从证书的私钥创建了 RsaSecurityKey 并将其用于添加签名凭证。在这种情况下,处置不会破坏任何东西。

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

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

所以我的问题比较笼统。我应该处理从现有证书创建的 X509Certificate2 对象吗?


来自 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.

最佳答案

查看.NET Core源码,X509Certificate2及其基类X509Certificate使用类CertificatePal来处理证书。 <强> CertificatePal 类支持从各种来源创建类的对象:blob、文件、证书存储。它在创建对象时调用 Windows CryptoAPI 来获取证书的句柄。因此,在使用该对象之后,有必要释放句柄指向的资源。好消息是,句柄存储在 SafeCertContextHandle 对象中,保证在垃圾收集器收集到 X509Certificate2 对象并完成调用终结器后关闭句柄对象。我的理解是,我们不需要手动调用 Dispose 方法。

关于c# - 我应该处理 X509Certificate2 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56337434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com