Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Export certificates from Azure Key Vault using PowerShell

While working with Azure Key Vault Certificate Create Azure Key Vault Certificates on Azure Portal and Powershell, Next requirement was to download those certificates from Key Vault. On the Azure Portal choose the SSL Certificate you want to export. Click buttons Download in CER format or Download in PFX/PEM format. 

Microsoft Azure Key Vault Portal certificate activation date subject enabled subject issure CN= sercial dns x.509 sha-1 key identifier secret identifier.png

PowerShell

Here I have written a PowerShell script to perfom the same task for one of my orchestration project, to either download certificate as Pfx or Cer format there are parameter with same names. Below are the example how to execute the script.

Microsoft Azure Key Vault certificate export Powershell az module Get-AzKeyVaultSecret X509Certificates Cryptography Write-Host pfx cer X509ContentType collection WriteAllBytes.png

.\Export-AzKeyVaultCertificate.ps1 -Path C:\temp\certs -CertificateName vcloud-lab-Automation-Account-Ps -KeyVaultName vcloudvault -Cer
.\Export-AzKeyVaultCertificate.ps1 -Path C:\temp\certs -CertificateName vcloud-lab-Automation-Account-Ps -KeyVaultName vcloudvault -PfxCertPassword '$ecret1' -Pfx  

Download this script here, this script is also available on github.com.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com',
    DefaultParameterSetName = 'pfx'
)]

<#
    .SYNOPSIS
    Export Azure key vault certificates to file.

    .DESCRIPTION
    Download/Export certificate files from Azure Key vault, it downloads certificate in cer or pfx extension format

    .PARAMETER Path
    Speciry Directory path to donwload/export Azure Key Vault certificate files.

    .PARAMETER CertificateName
    Specify Name of the Azure KeyVault Certificate.

    .PARAMETER KeyVaultName
    Specify Name of the Azure Key Vault Where certificate is stored.

    .PARAMETER Pfx
    This parameter exports certificate file in PFX extension format.

    .PARAMETER Cer
    This parameter exports certificate file in CER extenstion format.

    .PARAMETER PfxCertPassword
    If you are using PFX to export certificate, mention Password with this parameter.

    .INPUTS
    None. Export Azure key vault certificates to file.

    .OUTPUTS
    Export Azure key vault certificates to file in given path.

    .EXAMPLE
    PS> .\Export-AzKeyVaultCertificate.ps1 -Path C:\temp\certs -CertificateName vcloud-lab-Automation-Account-Ps -KeyVaultName vcloudvault -PfxCertPassword 123456 -Pfx
    This example to Export certificate in Pfx file format

    .EXAMPLE
    PS> .\Export-AzKeyVaultCertificate.ps1 -Path C:\temp\certs -CertificateName vcloud-lab-Automation-Account-Ps -KeyVaultName vcloudvault -Cer
    This example to Export certificate in Cer file format

    .LINK
    Online version: http://vcloud-lab.com
    http://vcloud-lab.com/entries/microsoft-azure/-create-azure-key-vault-certificates-on-azure-portal-and-powershell

    .LINK
    Export-AzKeyVaultCertificate.ps1
#>
Param
( 
    [parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'cer' )]
    [parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'pfx' )]
    [alias('Directory')]
    [string]$Path = 'C:\Temp\certs',
    [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'cer' )]
    [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'pfx' )]
    [alias('Certificate')]
    [string]$CertificateName = 'vcloud-lab-Automation-Account-Ps',
    [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'cer' )]
    [parameter(Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'pfx' )]
    [string]$KeyVaultName = 'vcloudvault',
    [parameter(Position=2, ParameterSetName = 'pfx', Mandatory=$true)]
    [switch]$Pfx,
    [parameter(Position=3, ParameterSetName = 'pfx')]
    [string]$PfxCertPassword = '123456',
    [parameter(Position=2, ParameterSetName = 'cer', Mandatory=$true)]
    [switch]$Cer
) #Param
begin
{
    $testFolderPath = Test-Path $Path
    if ($testFolderPath -eq $false)
    {
        New-Item -Path $Path -ItemType Directory -Force | Out-Null
    }
    #Verify Azure Key Vault and Certificate
    $azKeyVault = Get-AzKeyVault -VaultName $KeyVaultName
    try {
        $azKeyVaultSecret = Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $CertificateName -ErrorAction Stop
    }
    catch {
        Write-Host "Error - Check KeyVault '$KeyVaultName' or Certificate '$CertificateName' doesnt Exist" -BackgroundColor DarkRed
        Break
    }
    
} #begin
process 
{
    #Prepare to export Azure Key Vault certificate to local file
    if (($null -eq $azKeyVault) -or ($null -eq $azKeyVaultSecret))
    {
        Write-Host "Error - Check KeyVault '$KeyVaultName' or Certificate '$CertificateName' doesnt Exist" -BackgroundColor DarkRed
        Break
    } #if (($null -eq $azKeyVault) -or ($null -eq $azKeyVaultSecret))
    else {
        Write-Host "Verified - Key Vault and Certificate exists - '$KeyVaultName' and '$CertificateName'" -BackgroundColor DarkGreen
        #Put KeyVault Certificate information in memory to export
        [PSCredential]$password = New-Object System.Management.Automation.PSCredential('vcloud-lab.com',$azKeyVaultSecret.SecretValue)
        $cert64TextString = [System.Convert]::FromBase64String($password.GetNetworkCredential().password)
        $x509CertCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
        $x509CertCollection.Import($cert64TextString, $null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)        
        if ($PSCmdlet.ParameterSetName -eq 'cer')
        {
            #Export Azure Key Vault certificate to .cer file
            $azKeyVaultCert = Get-AzKeyVaultCertificate -VaultName $keyVaultName -Name $CertificateName
            $azKeyVaultCertBytes = $azKeyVaultCert.Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
            $cerCertFile = "$certFolderPath\$CertificateName.cer"
            [System.IO.File]::WriteAllBytes($cerCertFile, $azKeyVaultCertBytes)
            Write-Host "Exported certificate to file - $certFolderPath\$CertificateName.cer"
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'pfx')
        {
            #Export Azure Key Vault certificate to .pfx file 
            $x509CertCollectionBytes = $x509CertCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $PfxCertPassword)
            $pfxCertFile = "$certFolderPath\$CertificateName.pfx"
            [System.IO.File]::WriteAllBytes($pfxCertFile, $x509CertCollectionBytes)
            Write-Host "Exported certificate to file - $certFolderPath\$CertificateName.cer"
        }
    } #else if (($null -eq $azKeyVault) -or ($null -eq $azKeyVaultSecret))
} #process
end {} #end

AzureCLI
Although I have written complete Powershell Script but I found using AzureCLI even easier to download Pfx or Cer certificates. It can be done using one liner, There are more parmeters given on the official MicroSoft website, worth checking and might be helpful to you - https://docs.microsoft.com/en-us/azure/key-vault/certificates/how-to-export-certificate?tabs=azure-cli.

az keyvault certificate download --file C:\temp\certificatename.cer --encoding DER --Name certificatename --vault-name keyvaultname
az keyvault secret download --file C:\temp\certificatename.pfx --encoding base64 --Name certificatename --vault-name keyvaultname

Microsoft Azure Powershell az keyvault certificate download secret download --file --encoding der base64 --name  --vault-name key vault azurecli az login.png

Useful Commands
Create key vault and secrets with access policies in Microsoft Azure
Working With Azure Key Vault Using Azure PowerShell and AzureCLI
Use Key Vault secret identifier url to get the secret value using Powershell
Use a Azure VM system assigned managed identity to access Azure Key Vault
Create an Azure App registrations in Azure Active Directory using PowerShell & AzureCLI
Get started and configure with certificate-based authentication in Azure
Create a Virtual machine on Microsoft Azure
PowerShell List All Azure Resverations
Powershell get the list of Azure Reservations Virtual Machines instances
Get the list Azure Reservation Catalog with PowerShell and AzureCLI

Go Back

Comment

Blog Search

Page Views

11240804

Follow me on Blogarama