gpt4 book ai didi

c# - 区分根 CA 和中间 CA 证书

转载 作者:太空宇宙 更新时间:2023-11-03 12:01:12 38 4
gpt4 key购买 nike

我已经设法弄清楚 x509Certificate2Collection 中的证书是否是证书颁发机构证书,但我如何才能安全地确定它是根证书还是中间证书?以下是否足够安全?

var collection = new X509Certificate2Collection();
collection.Import("test.pfx", "password", X509KeyStorageFlags.PersistKeySet);

foreach (X509Certificate2 cert in collection)
{
var basicConstraintExt = cert.Extensions["2.5.29.19"] as X509BasicConstraintsExtension;
if (basicConstraintExt != null)
{
Log.Debug($" Subject is: '{cert.Subject}'");
Log.Debug($" Issuer is: '{cert.Issuer}'");
if (basicConstraintExt.CertificateAuthority)
{
Log.Debug("I am a CA Cert.");
if (cert.Subject == cert.Issuer)
{
Log.Debug("My Subject matches Issuer.");
}
else
{
Log.Debug("My Subject does not match Issuer.");
}
Log.Debug(cert.Verify() ? "I verify" : "I do not verify");
}
else
{
Log.Debug("I am not a CA Cert.");
}
}
}

结果:

 Displaying Cert #1 in collection
********************************

Subject is: 'CN=Intermediate-CA, DC=test, DC=lan'
Issuer is: 'CN=Root-CA, DC=test, DC=lan'
- I am a CA Cert.
- My Subject does not match Issuer.
- I do not verify


Displaying Cert #2 in collection
********************************

Subject is: 'CN=Root-CA, DC=test, DC=lan'
Issuer is: 'CN=Root-CA, DC=test, DC=lan'
- I am a CA Cert.
- My Subject matches Issuer.
- I do not verify

最佳答案

不确定这对 Kestrel 是否有帮助,但我会尝试下面的代码。

我们将使用 X509Chain类来构建和验证链。

var collection = new X509Certificate2Collection();
collection.Import("test.pfx", "password");

var chain = new X509Chain();
chain.ChainPolicy.ExtraStore.AddRange(collection);
// untrusted root error raise false-positive errors, for example RevocationOffline
// so skip possible untrusted root chain error.
chain.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
// revocation checking is client's responsibility. Skip it.
chain.RevocationMode = X509VerificationFlags.NoCheck;
// build the chain.
Boolean isValid = chain.Build(collection[0]);
// explore chain.ChainElements collection. First item should be your leaf
// certificate and last item should be root certificate

所有这些东西都位于 System.Security.Cryptography.X509Certificates 命名空间中。在这段代码中,我假设 PFX 中的第一个证书是叶证书(在 99% 的情况下是这样,除非有人试图忽略标准)。通过探索 chain.ChainElements 集合,您可以发现链中每个证书的问题。

关于c# - 区分根 CA 和中间 CA 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56886225/

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