从文件夹加载X509证书
我正在使用c#,并且需要从文件夹中加载X509证书。我需要从文件夹中加载文件以显示在加密程序内部的表中。
public partial class Form1 : Form
{
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var store = new X509Store(StoreName.My, storeLocation: StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
DataColumn dc1 = new DataColumn("Name", typeof(string));
DataColumn dc2 = new DataColumn("E-mail", typeof(string));
DataColumn dc3 = new DataColumn("valid from", typeof(string));
DataColumn dc4 = new DataColumn("Expiry Date", typeof(string));
DataColumn dc5 = new DataColumn("ThumbPrint", typeof(string));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
foreach (X509Certificate2 mCert in store.Certificates)
{
string email1 = mCert.GetNameInfo(X509NameType.SimpleName, false);
string stringAfterChar = email1.Substring(email1.IndexOf("-") + 1);
string name = mCert.GetNameInfo(X509NameType.SimpleName, false);
string[] splitString = name.Split('-');
string namewithoutemail = splitString[0].Trim();
dt.Rows.Add(namewithoutemail , stringAfterChar, mCert.NotBefore, mCert.GetExpirationDateString() , mCert.Thumbprint);
}
dataGridView1.DataSource = dt;
}
这是我的代码,实际上我可以从CertificateStore加载证书,但是我想从folder.Other加载证书,我可以为其程序创建一个特殊的证书存储,但是我认为这是不可能的。 感谢您的帮助
答案 0 :(得分:1)
请参阅X509Certificate2.Import的参考。这使您可以从文件系统中加载证书(以及其他方法)。在这种情况下,您只需要遍历文件夹中的证书文件,而不用打开CertificateStore。
foreach (var file in Directory.GetFiles(yourFolder, "*.cer"))
{
var mCert = X509Certificate2.Import(file);
string email1 = mCert.GetNameInfo(X509NameType.SimpleName, false);
string stringAfterChar = email1.Substring(email1.IndexOf("-") + 1);
string name = mCert.GetNameInfo(X509NameType.SimpleName, false);
string[] splitString = name.Split('-');
string namewithoutemail = splitString[0].Trim();
dt.Rows.Add(namewithoutemail , stringAfterChar, mCert.NotBefore, mCert.GetExpirationDateString() , mCert.Thumbprint);
}