Search code examples
c#x509certificate2certutil

Add certificate to Trusted Publisher programmatically


I have a usb driver which is signed. I also have the certificate provided by the publisher. If I try to install the driver with pnputil

pnputil /add-driver CerttName.cer /install

I'm asked if I want to add the publisher to Trusted Publishers.

To avoid it I tried to add the certificate to Trusted Publishers programmatically

string file = @"C:\Certificates\CertName.cer";
X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(new X509Certificate2(X509Certificate2.CreateFromCertFile(file)));
store.Close();

The certificate has been added but I'm still prompted by pnputil to add the publisher to Trusted Publishers.

If I use certutil

certutil -addstore "TrustedPublisher" CertName.cer

then I'm not prompted by pnputil.

I also tried to import the certificate manually from certmgr.msc but it also didn't work.

I don't understand why only certutil works and other ways (specially X509Store) not.


Solution

  • The problem is that you are installing the certificate in CurrentUser store, while it must be presented in LocalMachine store. Certutil defaults to local machine.

    X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);