How to remove certificate from Store cleanly

后端 未结 3 761
小蘑菇
小蘑菇 2021-02-13 11:03

You can install certificate into certificate store using Wizard in certmgr.msc (Right click install)? Does anyone knows how to \"cleanly\" remove all the certificate by either u

3条回答
  •  花落未央
    2021-02-13 11:10

    You could try the X509Store and releated classes in the .Net Framework to delete a certificate from the certificate store. The following code example deletes a certificate from the current user's My store:

    // 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();
    

    BEGIN EDIT: Based on the comments in the comment section I've updated my answer with a code sample showing how to remove a certificate and all certificates in the chain:

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

    END EDIT

    Hope, this helps.

提交回复
热议问题