0

I am able to load certificates that are available on my windows machines in a ListView using C# and by selecting a certificate, I added a functionality to delete a selected certificate using the code below:

    CertificateUtility util = new CertificateUtility();
    util.StoreName = Convert.ToString(this.drpdwnStores.SelectedValue);
    X509Store x509Store = new X509Store(util.StoreName, StoreLocation.LocalMachine);
    x509Store.Open(OpenFlags.OpenExistingOnly);
    X509Certificate2Collection certColl = x509Store.Certificates.Find(
         X509FindType.FindBySerialNumber, "mycert", true);
    X509Certificate2 deletethis = certColl[0];

    if (deletethis != null) {
     x509Store.Remove(deletethis);
    }

This line x509Store.Remove(deletethis); give me Access denied.

I am an admin on this particular machine

Does anyone know how to fix this?

mpora
  • 1,411
  • 5
  • 24
  • 65
  • Please review [MCVE] guide on posting code. In particular provide information on what `RunAsUser` is expected to do and what exact line causes the error. Additionally clarify what permission are granted on certificates to the account you hope to run this code under. – Alexei Levenkov Apr 04 '20 at 00:10
  • You probably need administrator permissions. Especially for working with `StoreLocation.LocalMachine`. Are you running your app as administrator? Does your app ask for elevated permissions to perform this operation? – E. Moffat Apr 04 '20 at 00:13
  • I am an admin on the machine – mpora Apr 04 '20 at 00:14
  • @AlexeiLevenkov I had put the wrong code. – mpora Apr 04 '20 at 00:16
  • 1
    You probably need to pass in `ReadWrite` as an opening flag. i.e. `x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);` also, LocalMachine requires being elevated to write to. – vcsjones Apr 04 '20 at 00:19
  • @vcsjones what do you mean by 'LocalMachine requires being elevated to write to' – mpora Apr 04 '20 at 00:24
  • @mpora https://stackoverflow.com/questions/2818179/how-do-i-force-my-net-application-to-run-as-administrator – Alexei Levenkov Apr 04 '20 at 01:42
  • answer by @mpora is correct. You need to have local administrator permissions and use `OpenFlags.ReadWrite` access flag when opening the store. – Crypt32 Apr 04 '20 at 12:16

1 Answers1

0

I had to run Visual Studio as an Admin to be able to debug the code and also added @vcsjones suggestion and the final code was as follows:

X509Store x509Store = new X509Store("My", StoreLocation.LocalMachine);
x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
X509Certificate2Collection certColl = x509Store.Certificates.Find( X509FindType.FindBySerialNumber, "serial", true);
if(certColl.Count > 0) {
  X509Certificate2 deletethis = certColl[0];
  if (deletethis != null)
   {
    x509Store.Remove(deletethis);
   }
}

I also had to add a manifest file and add this line:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
mpora
  • 1,411
  • 5
  • 24
  • 65