c# - 如何从商店中干净地删除证书

标签 c# vb.net powershell x509certificate wizard

您可以使用 certmgr.msc 中的向导将证书安装到证书存储中(右键单击安装)?有谁知道如何使用向导/代码(首选)/脚本“干净地”删除所有证书?

我希望能够从 LocalMachine 和/或 CurrentUser Store 中删除所有内容(我之前安装的)而不留下任何残留物。

谢谢

最佳答案

您可以尝试使用 X509Store 和 .Net Framework 中的相关类从证书存储中删除证书。以下代码示例从当前用户的我的商店中删除证书:

// Use other store locations if your certificate is not in the current user store.
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);

// You could also use a more specific find type such as X509FindType.FindByThumbprint
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, "yoursubjectname", false);

foreach (var cert in col)
{
  Console.Out.WriteLine(cert.SubjectName.Name);

  // Remove the certificate
  store.Remove(cert);        
}
store.Close();

开始编辑: 根据评论部分的评论,我用一个代码示例更新了我的答案,该示例显示了如何删除证书和链中的所有证书:

  X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, "yoursubjectname", false);

  X509Chain ch = new X509Chain();
  ch.Build(col[0]);
  X509Certificate2Collection allCertsInChain = new X509Certificate2Collection();

  foreach (X509ChainElement el in ch.ChainElements)
  {
    allCertsInChain.Add(el.Certificate);
  }

  store.RemoveRange(allCertsInChain);

结束编辑

希望这对您有所帮助。

关于c# - 如何从商店中干净地删除证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7632757/

相关文章:

c# - ZeroMQ Poll 函数是否在 .NET 上使用了过多的 CPU?

c# - async 在这个例子中有什么好处吗?

javascript - __doPostBack 在 safari 或 firefox 中不起作用,在 IE 中起作用

powershell - 带括号的环境变量导致 “unexpected token”错误

powershell - Powershell ConvertTo-json输出为小写

c# - UWP 中的位图平滑

c# - 具有多个组分隔符的 Int32.TryParse

vb.net - 无法在 dropdownList 控件中显示记录

.net - xmlns 元素的顺序是否重要

regex - 在文件中搜索RegEx字符串,仅返回文件名,路径和字符串