从 C# 中的证书存储中获取证书列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1205295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:51:35  来源:igfitidea点击:

Get list of certificates from the certificate store in C#

c#certificatex509certificatecertificate-store

提问by

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? Thanks in advance for your help.

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

回答by Steve Gilham

Yes -- the X509Store.Certificatesproperty returns a snapshot of the X.509 certificate store.

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

回答by acejologz

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

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}

回答by Cobaia

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

回答by Roni Fuchs

The simplest way to do that is by opening the certificate store you want and then using X509Certificate2UI.

最简单的方法是打开所需的证书存储,然后使用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 X509Certificate2UIon MSDN.

X509Certificate2UIMSDN 上的更多信息。