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

大城市里の小女人 提交于 2019-11-26 18:24:50
Demi

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
}

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();
}

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();

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: Private key of certificate in certificate-store not readable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!