检索 X509Certificate2 对象的颁发者

Retrieving issuer of a X509Certificate2 object

我有一个 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,其中 .Issuer 有点误导,因为它返回的字符串基本上是发行人的名字。

这两个属性最多可以 return 一个 Distinguished Name but DNs are not unique, right? Therefore I don't want to use X509Certificate2Collection.Find method with X509FindType.FindByIssuerDistinguishedName 标志。

如何获得证书的颁发者并确保我有 "right one"。注意:我不必使用 X509Certificate2 对象。欢迎其他选择。

如果我没理解错的话,你有一个证书,你想找到颁发者证书。这可以按如下方式完成:

  1. 检查叶证书的 Subject 和 Issuer 字段是否不同。否则,证书就是颁发者(自签名证书)

  2. 实例化 X509Chain 对象并将叶证书传递给 X509Chain.Build 方法。检查 ChainElements 属性(一个集合),索引 1 处的元素是发行者。

    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;
        }
    }
    }