Reputation: 872
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.
Upvotes: 12
Views: 6812
Reputation: 13924
If I understand you correctly, you have a certificate and you want to find the issuer certificate. This can be done as follows:
Check if the leaf certificate's Subject and Issuer fields are not the same. Otherwise, the certificate is the issuer (self-signed certificate)
Instantiate 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;
}
return issuer;
}
}
}
Note that this only works if the issuer certificate is in the user or machine certificate store.
Upvotes: 19