Import certificate to store and grant rights with PowerShell

I will show you example how to import certificate to certificates store on computer. In my example I will use pfx certificate, but it doesn’t matter, you can also use *.cer. We will use .NET X509Certificate2 and X509Store classes do do all the work.

At first certificate object is created:

PersistKeySet is set to store certificate’s private key permanently.

Afterwards we get a certificate store and import the certificate to it:

With the same approach we can import to multiple certificate stores the same certificate.

Usually to use the certificate in .NET code you need to grant security rights for account on which app is running, so account could access the certificate’s private key. It can be local account, system account or domain account, but the way to do that is the same.

You need to install WinHttpCertCfg (certificate configuration tool) on machine where your certificate exists and app is running. Default installation path on 64 bit windows is “C:\Program Files (x86)\Windows Resource Kits\Tools”.

After tool is installed needs to run command similar to

winhttpcertcfg.exe -g -c LOCAL_MACHINE\MY -s Test -a “NETWORK SERVICE”

To execute such command in PS you need prefix it with &

If granting succeeds you will get such message:

Matching certificate:

Granting private key access for account:

So whole import PS script will be

If you see any mistake or improvement point, please write it below in the comment. Thanks.

1 thought on “Import certificate to store and grant rights with PowerShell

Leave a Reply

Your email address will not be published.