获取本地计算机上安装的所有证书

时间:2017-07-15 09:04:49

标签: c# ssl-certificate x509certificate

我有以下代码来获取证书:

X509Store store = new X509Store("??","??");
            List<X509Certificate2> lst = new List<X509Certificate2>();
            store.Open(OpenFlags.ReadOnly);

            foreach (X509Certificate2 mCert in store.Certificates)
            {

                lst.Add(mCert);
                //TODO's
            }
  

现在我希望在本地计算机中安装所有证书   列表&lt;&gt;凭证书名称,他们的位置,用公钥发行   或私钥(仅限是或否)和文件夹的名称   包含这些证书(请参阅下面的快照):

enter image description here

填充List&lt;&gt;之后使用Certs详细信息我想以网格格式显示这些数据。如何修改此代码以获取上述详细信息?

2 个答案:

答案 0 :(得分:2)

您计算机上的证书存储在不同的商店中,因此您需要打开所有商店。请看MSDN  制品

代码示例:

public class CertDetails
{
    public string Name { get; set; }
    public string HasPrivateKey { get; set; }
    public string Location { get; set; }
    public string Issuer { get; set; }
}

// stores and they friendly names
var stores = new Dictionary<StoreName, string>()
{
    {StoreName.My, "Personal"},
    {StoreName.Root, "Trusted roots"},
    {StoreName.TrustedPublisher, "Trusted publishers"}
    // and so on
    }.Select(s => new {store = new X509Store(s.Key, StoreLocation.LocalMachine), location = s.Value}).ToArray();

foreach (var store in stores)
    store.store.Open(OpenFlags.ReadOnly); // open each store

var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>()
    .Select(mCert => new CertDetails
    {
        HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
        Name = mCert.FriendlyName,
        Location = s.location,
        Issuer = mCert.Issuer
    })).ToList();

答案 1 :(得分:1)

一个简短的灵感示例,也许有点帮助:

using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
...
X509Store store = null;
store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly)
...

//RSA CryptoServiceProvider
RSACryptoServiceProvider rsaCSP = null;

string keyPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Microsoft\Crypto\RSA\MachineKeys\";

string friendlyName = "";

foreach (X509Certificate2 mCert in store.Certificates) {

  rsaCSP = mCert.PrivateKey as RSACryptoServiceProvider;

  if (rsaCSP != null) {
    friendlyName = mCert.FriendlyName;                    
    keyPath += rsaCSP.CspKeyContainerInfo.UniqueKeyContainerName;
  }                        
}