X509Chain.Build(...) System.InvalidCastException 从 X509Certificate 到 X509Certificate2

Posted

技术标签:

【中文标题】X509Chain.Build(...) System.InvalidCastException 从 X509Certificate 到 X509Certificate2【英文标题】:X509Chain.Build(...) System.InvalidCastException from X509Certificate to X509Certificate2 【发布时间】:2022-01-21 19:14:30 【问题描述】:

我正在尝试使用自定义证书颁发机构验证证书链。为什么这段代码最后一行会抛出异常?

using System.Security.Cryptography.X509Certificates;

string BaseCertsDir = "Certificates\\";

X509Certificate serverCrt = new(BaseCertsDir + "Server\\Server.crt");
X509Certificate intermediateCert = new(BaseCertsDir + "IntermediateCA\\IntermediateCA.crt");
X509Certificate rootCert = new(BaseCertsDir + "RootCA\\RootCA.crt");

X509Chain chain = new();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Clear();
chain.ChainPolicy.CustomTrustStore.Add(rootCert);

chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

chain.ChainPolicy.ExtraStore.Add(intermediateCert);

chain.Build(new X509Certificate2(serverCrt));

例外:

Exception thrown: 'System.InvalidCastException' in System.Private.CoreLib.dll
An unhandled exception of type 'System.InvalidCastException' occurred in System.Private.CoreLib.dll
Unable to cast object of type 'System.Security.Cryptography.X509Certificates.X509Certificate' to type 'System.Security.Cryptography.X509Certificates.X509Certificate2'.

【问题讨论】:

【参考方案1】:

在添加之前,我可以通过将 rootCertintermediateCert 转换为 X509Certificate2 来使代码正常工作:

chain.ChainPolicy.CustomTrustStore.Add(new X509Certificate2(rootCert));
chain.ChainPolicy.ExtraStore.Add(new X509Certificate2(intermediateCert));

【讨论】:

以上是关于X509Chain.Build(...) System.InvalidCastException 从 X509Certificate 到 X509Certificate2的主要内容,如果未能解决你的问题,请参考以下文章

X509_STORE 和 X509_STORE_CTX 有啥区别?

x509证书格式

x509的简介

X.509

将 python x509 签名请求对象 (x509.CertificateSigningRequest) 对象转换为字节

X.509:私钥/公钥