Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 347
user3652261 Avatar asked Dec 12 '14 12:12

user3652261


2 Answers

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();
like image 116
user3652261 Avatar answered Nov 05 '22 22:11

user3652261


Try with this flag: store.Open (OpenFlags.ReadWrite);

http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.openflags(v=vs.110).aspx

like image 1
Erik Oppedijk Avatar answered Nov 05 '22 22:11

Erik Oppedijk