How can I install a certificate in a local repository of programs using C #?

I have a certificate generated through MakeCert. I want to use this certificate to secure WCF messages with PeerTrust. How can I programmatically install a certificate in the trust store of the local computer certificate store using C # or .NET?

I have a CER file, but you can also create a PFX.

+52
c # certificate wcf makecert
Feb 19 '09 at 18:32
source share
4 answers

I believe this is correct:

using (X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadWrite); store.Add(cert); //where cert is an X509Certificate object } 
+55
Feb 19 '09 at 20:42
source share

The following works for me:

 private static void InstallCertificate(string cerFileName) { X509Certificate2 certificate = new X509Certificate2(cerFileName); X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(certificate); store.Close(); } 
+38
Sep 10 '09 at 10:15
source share

Instead of installing a certificate in LocalMachine, which requires elevated privileges, you can add it to "CurrentUser" (works for me).

 X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Add(cert); //where cert is an X509Certificate object store.Close(); 
+7
Sep 13 '13 at 8:56
source share

I had to use X509KeyStorageFlags. PersistKeySet | X509KeyStorageFlags. MachineKeySet flags to resolve the "Keyset does not exist" error that occurred later when trying to use the certificate:

 X509Certificate2 certificate = new X509Certificate2(pfxPath, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadWrite); store.Add(certificate); store.Close(); } 

Thanks to this article: the private key of the certificate in the certificate store is not readable

0
Jul 05 '18 at 16:37
source share



All Articles