Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving issuer of a X509Certificate2 object

I have a X509Certificate2 object retrieved from X509Store. I want to get the issuer of this certificate but the only two properties that this object offers are X509Certificate2.Issuer and X509Certificate2.IssuerName where .Issuer is kinda misleading as it returs string that is basically issuer's name.

Both those properties can at most return a Distinguished Name but DNs are not unique, right? Therefore I don't want to use X509Certificate2Collection.Find method with X509FindType.FindByIssuerDistinguishedName flag.

How can I get a certificate's issuer and be sure I have the "right one". Note: I don't have to use X509Certificate2 object. Alternatives are welcome.

like image 881
Mike Avatar asked Oct 19 '15 16:10

Mike


1 Answers

If I understand you correctly, you have a certificate and you want to find the issuer certificate. This can be done as follows:

  1. check if the leaf certificate's Subject and Issuer fields are not the same. Otherwise, the certificate is the issuer (self-signed certificate)

  2. Instatniate X509Chain object and pass leaf certificate to X509Chain.Build method. Examine ChainElements property (a collection) and element at index 1 is the issuer.

    using System.Security.Cryptography.X509Certificates;
    
    namespace Name {
        class Class1 {
        public static X509Certificate2 GetIssuer(X509Certificate2 leafCert) {
            if (leafCert.Subject == leafCert.Issuer) { return leafCert; }
            X509Chain chain = new X509Chain();
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
            chain.Build(leafCert);
            X509Certificate2 issuer = null;
            if (chain.ChainElements.Count > 1) {
                issuer = chain.ChainElements[1].Certificate;
            }
            chain.Reset();
            return issuer;
        }
    }
    }
    
like image 135
Crypt32 Avatar answered Oct 19 '22 21:10

Crypt32