Reputation: 1297
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?
Upvotes: 1
Views: 13677
Reputation: 7054
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();
Upvotes: 3
Reputation: 162
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;
}
}
Upvotes: 1