For a secure application I need to select a certificate in a dialog.
How can I access certificate store or a part of it (e.g. storeLocation="Local Machine"
and storeName="My"
) using C# and get a collection of all certificates from there?
Asked
Active
Viewed 1.2e+01k times
49

starball
- 20,030
- 7
- 43
- 238
5 Answers
20
Try this:
//using System.Security.Cryptography.X509Certificates;
public static X509Certificate2 selectCert(StoreName store, StoreLocation location, string windowTitle, string windowMsg)
{
X509Certificate2 certSelected = null;
X509Store x509Store = new X509Store(store, location);
x509Store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = x509Store.Certificates;
X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, windowTitle, windowMsg, X509SelectionFlag.SingleSelection);
if (sel.Count > 0)
{
X509Certificate2Enumerator en = sel.GetEnumerator();
en.MoveNext();
certSelected = en.Current;
}
x509Store.Close();
return certSelected;
}

Cobaia
- 1,503
- 3
- 22
- 41
-
13Linq makes this easier: x509Store.Certificates.OfType
().FirstOrDefault(cert => cert.IssuerName.Name.EndsWith("DC=mysite, DC=com")); – Jonathan DeMarks Mar 28 '12 at 12:31 -
@JonathanDeMarks: what exactly does the `"DC=mysite, DC=com"` signify here? None of these examples seem to show how to get a _specific_ certificate... – Nyerguds Jun 27 '13 at 09:32
-
@Nyerguds The question is: Get list of certificates from the certificate store in C#, not specific. Please, Create another question. – Cobaia Jun 27 '13 at 11:27
11
The simplest way to do that is by opening the certificate store you want and then using X509Certificate2UI
.
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var selectedCertificate = X509Certificate2UI.SelectFromCollection(
store.Certificates,
"Title",
"MSG",
X509SelectionFlag.SingleSelection);
More information in X509Certificate2UI
on MSDN.

Roni Fuchs
- 271
- 3
- 5
-
1To use `X509Certificate2UI` I need to add a reference to `System.security.dll`, however this works like a charm +1 `:)`. Also to use a user keystore I use `StoreLocation.CurrentUser` instead of`StoreLocation.LocalMachine`. – albciff May 21 '15 at 09:42
4
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.

Steve Gilham
- 11,237
- 3
- 31
- 37
1
Example for the above question.
public List<string> getListofCertificate()
{
var certificates = new List<string>();
X509Store store = new X509Store(StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
// Place all certificates in an X509Certificate2Collection object.
X509Certificate2Collection certCollection = store.Certificates;
foreach (X509Certificate2 x509 in certCollection)
{
Console.WriteLine(x509.IssuerName.Name);
certificates.Add(x509.IssuerName.Name);
}
}
finally
{
store.Close();
}
return certificates;
}

Mohammed Niyas
- 11
- 2