Search code examples
c#x509x509certificate2

Given two X509Certificate2 objects in C#, how can I check whether one issued the other?


I have a C# application where we make our own certificate chains based on our own root certificates.

Given a root certificate c1 and an issued certificate c2, I want to check whether c2 was issued by c1 - i.e., whether c1 is the "parent" of c2 and that the two can form a valid chain.

How can I check this?

I am using .NET 6. Thanks in advance!


Solution

  • A possible method is, to create a chain from c2 and check inside the chain, if the root certificate is present (By comparing the Thumbprint):

    private static bool CheckCertChain(X509Certificate2 rootCert, X509Certificate2 clientCert)
            {
                X509Chain chain = new X509Chain();
                //Need to set revocation to no check
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                //Build the chain
                if (!chain.Build(clientCert))
                    return false;
                //Check if the root is present in the chain
                return chain.ChainElements.Cast<X509ChainElement>().Any(cert => cert.Certificate.Thumbprint.Equals(rootCert.Thumbprint, StringComparison.InvariantCultureIgnoreCase));
            }