Adding a Certificate to x509Store doesn't do anything C#

5.2k views Asked by At

I'm trying to add certificates but the Add function doesn't seem to do anything.

I have two certificates. Both I can add manually by right clicking and saving to the personal "testStore" store but they don't get saved when I try to add them programmatically. I even added just one of them, and the X509Store object contains it just as expected, but when I call .Add(cert), nothing gets saved there.

//I've already added 1 cert manually
X509Certificate2 cert2 = new X509Certificate2(@"C:\temp\Cert2.cer");
X509Store store = new X509Store("testStore", StoreLocation.CurrentUser);
store.Open(OpenFlags.MaxAllowed);

//here store.Certificates has the one Certificate I added manually as expected.

store.Certificates.Add(cert2);

//here store.Certificates still only has the first certificate, cert2 still isn't there..

store.Close();

Am I missing something?

Edit I've also tried using StorePermission (as below) and also tried impersonating the administrator account and those didn't help either

StorePermission sp = new StorePermission( PermissionState.Unrestricted);
sp.Flags = StorePermissionFlags.AllFlags;
sp.Assert();
2

There are 2 answers

0
Erik Oppedijk On
0
user3652261 On

I got it to work... It turns out you should use store.Add() instead of store.Certificates.Insert();

//When LocalMachine is used, .Add() requires that you run the app as an administrator in order to work.
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
X509Certificate2 cert = new X509Certificate2("C:\\test\\test.cer");
store.Open(OpenFlags.MaxAllowed);
store.Add(cert);
store.Close();