因为 CA 证书不在根证书存储中,所以您将在 RemoteCertificateValidationCallback() 中有一个 SslPolicyErrors.RemoteCertificateChainErrors 的错误标志;一种可能性是针对您自己的 X509Certificate2Collection 明确验证证书链,因为您没有使用本地存储。
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
{
X509Chain chain0 = new X509Chain();
chain0.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
// add all your extra certificate chain
chain0.ChainPolicy.ExtraStore.Add(new X509Certificate2(PublicResource.my_ca));
chain0.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
isValid = chain0.Build((X509Certificate2)certificate);
}
您还可以重新使用回调中传递的链,在 ExtraStore 集合中添加您的额外证书,并使用 AllowUnknownCertificateAuthority 标志进行验证需要,因为您将不受信任的证书添加到链中。
您还可以通过在受信任的根存储中以编程方式添加 CA 证书来防止原始错误(当然它会打开一个弹出窗口,因为全局添加新的受信任的 CA 根是一个主要的安全问题):
var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
X509Certificate2 ca_cert = new X509Certificate2(PublicResource.my_ca);
store.Add(ca_cert);
store.Close();
编辑:对于那些想用你的 CA 清楚地测试链的人:
另一种可能性是使用库BouncyCastle 来构建证书链并验证信任。选项很清楚,错误很容易理解。如果成功,它将构建链,否则返回异常。下面的示例:
// rootCerts : collection of CA
// currentCertificate : the one you want to test
var builderParams = new PkixBuilderParameters(rootCerts,
new X509CertStoreSelector { Certificate = currentCertificate });
// crls : The certificate revocation list
builderParams.IsRevocationEnabled = crls.Count != 0;
// validationDate : probably "now"
builderParams.Date = new DateTimeObject(validationDate);
// The indermediate certs are items necessary to create the certificate chain
builderParams.AddStore(X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(intermediateCerts)));
builderParams.AddStore(X509StoreFactory.Create("CRL/Collection", new X509CollectionStoreParameters(crls)));
try
{
PkixCertPathBuilderResult result = builder.Build(builderParams);
return result.CertPath.Certificates.Cast<X509Certificate>();
...