检索 X509Certificate2 对象的发行者

10

我有一个从X509Store检索到的X509Certificate2对象。我想获取此证书的颁发者,但该对象提供的仅有两个属性是X509Certificate2.IssuerX509Certificate2.IssuerName,其中.Issuer有点误导,因为它返回的字符串基本上是颁发者的名称。

这两个属性最多只能返回一个可分辨名称,但是DN不是唯一的,对吧?因此,我不想使用X509Certificate2Collection.Find方法和X509FindType.FindByIssuerDistinguishedName标志。

我该如何获取证书的颁发者并确保我有“正确的”颁发者?注意:我不必使用X509Certificate2对象。欢迎提供替代方案。

1个回答

17
如果我理解您的意思正确,您拥有一个证书并想找到发行者证书。操作步骤如下:
  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. 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.


1
就是这样!X509Chain 是解决方案。 - Mike
2
只有在您拥有发行者证书的访问权限时,此操作才能生效。 - spongyryno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接