How can I install a certificate into the local machine store programmatically using c#?

C#.NetWcfCertificateMakecert

C# Problem Overview


I have a certificate generated via MakeCert. I want to use this certificate for WCF message security using PeerTrust. How can I programmatically install the certificate into the "trusted people" local machine certificate store using c# or .NET?

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

C# Solutions


Solution 1 - C#

I believe that 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
}

Solution 2 - C#

The following works good 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();
}

Solution 3 - C#

Instead of installing the certificate to 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();

Solution 4 - C#

I had to use X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet flags to resolve "Keyset does not exist" error that occurred later on attempt 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: https://stackoverflow.com/questions/13231858/private-key-of-certificate-in-certificate-store-not-readable

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ DavisView Question on Stackoverflow
Solution 1 - C#DemiView Answer on Stackoverflow
Solution 2 - C#Olexander IvanitskyiView Answer on Stackoverflow
Solution 3 - C#user1799563View Answer on Stackoverflow
Solution 4 - C#DmitryView Answer on Stackoverflow