Get all certificates installed on Local machine

我是研究僧i 提交于 2019-12-11 06:24:38

问题


I have the following code to get the certificates:

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
            }

Now I want to get all the certificates installed on Local Machine in a list<> with Certificate Name, Their location, Issued with Public key Or Private Key(in Yes or No only) and the name of folder which contains those certs(please refer below snapshot):

After populating List<> with Certs details I want to display those data in a grid format. How to modify this code to get above details?


回答1:


Certificates on your machine stored in a different stores, so you need open all of them. Please see that MSDN article.

Code example:

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();



回答2:


A short example for your inspiration, maybe it helps a bit:

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


来源:https://stackoverflow.com/questions/45116450/get-all-certificates-installed-on-local-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!