区分根CA和中级CA证书

时间:2019-07-04 10:42:04

标签: c# ssl .net-core x509certificate2

我设法弄清楚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

1 个答案:

答案 0 :(得分:1)

不确定这是否对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集合,您可以找到链中每个证书的问题。