Code-Signing Mini-Series (Part 2: Reading Certificates from PFX Files)

by Nov 29, 2018

In the previous tip we created new code-signing test certificates both as pfx file and located in your certificate store. Today, you’ll see how you can load these (or any other certificates you got from other sources) into PowerShell.

To load a certificate from a pfx file, use Get-PfxCertificate:

$Path = "$home\desktop\tobias.pfx"
$cert = Get-PfxCertificate -FilePath $Path 

$cert | Select-Object -Property *

Get-PfxCertificate will prompt you for the password you defined when the pfx file was created. Some pfx files do not use password protection or protect the certificate via your user account identity in which case no prompt appears.

If you need to automate loading pfx certificates, here is a function that accepts a password by argument, and can load certificates from pfx files unattended:

function Load-PfxCertificate
{
  param
  (
    [String]
    [Parameter(Mandatory)]
    $FilePath,
    
    [SecureString]
    [Parameter(Mandatory)]
    $Password
  )
  
  # get clear text password
  $plaintextPassword = [PSCredential]::new("X", $Password).GetNetworkCredential().Password
  
  
  [void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
  $container = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
  $container.Import($FilePath, $plaintextPassword, 'PersistKeySet')
  $container[0]
}

And this is how the function works:

 
PS C:\> $pwd = 'secret' | ConvertTo-SecureString -AsPlainText -Force
PS C:\> $path = "$home\desktop\tobias.pfx"
PS C:\> $cert = Load-PfxCertificate -FilePath $path -Password $pwd

PS C:\> $cert

Thumbprint                                Subject                              
----------                                -------                              
322CA0B1F37F43B26D4D8DE17DCBF3E2C17CE111  CN=Tobias 
 

When you look at the last line in Load-PfxCertificate, you can easily adapt the function to pfx files that contain more than one certificate. The function always returns the first certificate ($container[0]), but you could as well pick any other index number.

Join our next tip to find out how to access certificates stored in your personal certificate store.

Twitter This Tip! ReTweet this Tip!