Delete any cert of certmgr without FriendlyName or <None>

167 views Asked by At

I I'm having trouble making a filter that deletes any cert that doesn't have firendlyname from my certificate store in general.

Im using c# console.

I tried that but it doesn't seem to be doing anything. Still not doing anything about what I want, does anyone have a solution, thank you.

private static void RemoveUnwantedCert()
    {
        // Open the Root store
        string RootStoreName = "Root";
        StoreLocation RootStoreLocation = StoreLocation.LocalMachine;
        X509Store RootStore = new X509Store(RootStoreName, RootStoreLocation);
        RootStore.Open(OpenFlags.ReadOnly);

        // Get all certificates in the Root store
        X509Certificate2Collection certificates = RootStore.Certificates;

        // Loop through all the certificates in the Root store
        foreach (X509Certificate2 certificate in certificates)
        {
            if (certificate.FriendlyName == "None")

                try
                {
                    // Open the Root store again, this time with ReadWrite permissions
                    RootStore.Open(OpenFlags.ReadWrite);
                    // Remove the certificate from the Root store
                    RootStore.Remove(certificate);
                    // Close the Root store
                    RootStore.Close();
                }
                catch (Exception) { }
            // Break out of the loop
            break;

        }

        // Close the Root store
        RootStore.Close();
        
```
`

I tried that but it doesn't seem to be doing anything. Still not doing anything about what I want, does anyone have a solution, thank you.

2

There are 2 answers

3
qqus On

To remove a certificate and all certificates in the chain -

   X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, "yoursubjectname", false);
    
      var chain = new X509Chain();
      chain.Build(col[0]);
      var allCertsInChain = new X509Certificate2Collection();
    
      foreach (var entry in chain.ChainElements)
      {
        allCertsInChain.Add(entry.Certificate);
      }
    
      store.RemoveRange(allCertsInChain);
1
Raphael On

Thanks but i just want delete a specified one.