Wednesday, July 6, 2011

Adding a Certificate to the Trusted Root CA Store using PowerShell

Here is a little reminder for myself.

My scenario is that I am adding a simple public certificate to a Local Computer certificate store.  And I need to script it with PowerShell.

I have actually been searching around for this one for a bit and all the results I find make it seem really really complex and complicated and it isn’t.  But there are some gotchas that need to be dealt with.

Here is the script:

$certFile = get-childitem $exPath | where {$_.Extension -match "cer"}
if ($certFile -ne $NULL) {
    "Discovered a .cer in the same folder as this script, installing it in the LocalMachine\Root certificate store.."
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certFile.FullName)
    $store = get-item Cert:\LocalMachine\Root
    $store.Open("ReadWrite")
    $store.Add($cert)
    $store.Close()
}

$exPath is the path where my script is executing.  I get that with: $exPath = Split-Path -parent $MyInvocation.MyCommand.Definition

The gotchas are: 

  • Getting the certificate as a certificate object – notice that when I get $cert I am actually getting the $certFile object as a new object that is a certificate, not a file.
  • Opening the store – if you try $store.Add without opening it read/write you actually get a really strange .ctor (a constructor) error.

I use this to include a private Root Certificate Authority with my Azure Service.  I simply add the .cer to the same folder in the Role project as my PowerShell script and publish.

I have my Azure Service certificate and private key being injected by the Azure Fabric and I use this little loop to add my Private Certificate Authority Certificate to the Local Machine Trusted Root Certificate Authorities store.  Thus completing my certificate chain and making my certificate useful – without buying a public certificate or messing with a wildcard public certificate.

No comments: