≡ Menu

Scripting the import of a X.509 certificate (.PFX file) into a Windows Certificate Store

Importing a X.509 certificates into a Windows Certificate Store and granting a user access to it can be a real pain. Especially if you have to do it on multiple machines!

Fear not, my friend: it can be automated, for both local and remote machines. I thought I might document how to do it because it took some time to get working.

The below script will:

  1. Check whether the certificate (.pfx file) is already in the certificate store
  2. If not already there, import the certificate
  3. Find the key via its thumbprint, using Microsoft’s FindPrivateKey tool
  4. Grant a user access to the key

NOTE: the below script is strictly illustrative – error handling and commenting are left as exercises for the reader ;)

@echo off

set user=%1
set thumbprint=%2
set file_name=%3
set password=%4

for /F "delims=" %%i in ('"FindPrivateKey.exe" My LocalMachine -t %thumbprint% -a') do SET certpath=%%i

if defined %certpath% goto grantaccess
certutil -f -p %password% -importpfx %file_name%

goto findcertificate

icacls.exe "%certpath%" /grant %user%:R

And that’s it.

If you cut and paste the above into a .bat file and name it something like install.bat, you can invoke it like this:
install.bat user_name footprint certificate_filename certificate_password
For example:
install.bat "IIS App Pool\AppPool1" bc4da1aa2b7116abe33277a44eaab2135210e23b certificate.pfx password

Some pre-requisites/gotchas:

  1. You will need Microsoft’s FindPrivateKey tool which will locate the certificate in the store. You can obtain FindPrivateKey in the WCF samples: download
  2. The script will locate the certificate by its footprint, which you will need to determine in advance by importing the certificate manually
  3. You can also use FindPrivateKey to locate the certificate by subject name, but I found that locating it by footprint was more reliable for multi-line subjects
  4. To grant access an IIS app pool access to the certificate, you need to specify the app pool name in the format
    "IIS App Pool\app_pool_name"

Installing the certificate on a remote machine

I used the SysInternals tool PSExec to run the script on remote machines, using the below parameters:
PSExec.exe /accepteula \\hostname -i -s -w remote_working_folder cmd /c "script_with_parameters"

  • hostname: the hostname on which the script will run
  • remote_working_folder: folder on the host which contains the certificate to import and the FindPrivateKey tool exe
  • script_with_parameters: the batch file to run with all parameters specified

For example:
PSExec.exe /accepteula \\myhost -i -s -w c:\temp cmd /c install.bat "IIS App Pool\AppPool1" bc4da1aa2b7116abe33277a44eaab2135210e23b certificate.pfx password"

Be Sociable, Share!
{ 0 comments… add one }

Leave a Comment