45

对于安全应用程序,我需要在对话框中选择一个证书。如何使用 C# 访问证书存储或其一部分(例如storeLocation="Local Machine"storeName="My")并从那里获取所有证书的集合?在此先感谢您的帮助。

4

5 回答 5

75
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}
于 2011-05-17T08:46:21.627 回答
20

尝试这个:

//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;
}
于 2011-07-26T13:25:40.860 回答
11

最简单的方法是打开所需的证书存储,然后使用X509Certificate2UI.

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var selectedCertificate = X509Certificate2UI.SelectFromCollection(
    store.Certificates, 
    "Title", 
    "MSG", 
    X509SelectionFlag.SingleSelection);

X509Certificate2UI有关MSDN的更多信息。

于 2015-03-15T14:21:02.417 回答
4

是 - 该X509Store.Certificates属性返回 X.509 证书存储的快照。

于 2009-07-30T09:00:19.930 回答
0

上述问题的示例。

    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;

    }
于 2021-07-22T08:14:04.470 回答