How to export KeyVault certificates from Azure?

Todays article will describe how easly download KeyVault certificates (including private keys) to your computer.
It can be very usefull in scenario where you want to authenticate to some web application but certificate is needed.
It is not so easy to download certificate, including private key directly from Azure portal – for me it was impossible 🙂
In first way you must define password which will be used to install certificate, path when certificate will be stored and login to Azure.

$password = 'MySuperSecretPassword'
$pfxPath = "d:\MyCert.pfx"
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionId 'subscriptionid'

In next step you must gather certificate and decode SecretValue attribute from base64 format. For more info regarding Base64 check Wikipedia


$kvSecret = Get-AzureKeyVaultSecret -VaultName 'VaultName' -Name 'certifiatename'
$kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)

Once it is done, create certificate collection object and import encoded value.
Certificate collection object gave possibility to gather full chain of certifiacte, including all roots certificates.

$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

After that, use Export method of certificates collection and use password provided at the beginning of the script.
Certificate will be saved in pkcs12 format.

$protectedCertificateBytes = $certCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $password)

To save certificate use WriteAllBytes method of System.IO.File class.

[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertificateBytes) 

Certificate and all roots certificates have been saved in path defined at the beginning of the script.
I hope this script will be usefull for some of you.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.