Azure Key Vault Export PFX Certificate

This PowerShell script will help you export a certificate in PFX format from Azure Key Vault. The certificate can also be exported via the Azure portal however it does not give you an option to set a password.

Change the following values to match your own requirements:

keyvault-name
certificate-name
new-password

$cert = Get-AzKeyVaultCertificate -VaultName "keyvault-name" -Name "certificate-name"
$secret = Get-AzKeyVaultSecret -VaultName "keyvault-name" -Name $cert.Name
$secretValueText = '';
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue)
try {
    $secretValueText = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
} finally {
    [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
}
$secretByte = [Convert]::FromBase64String($secretValueText)
$x509Cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2($secretByte,'','Exportable,PersistKeySet')
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx
$password = 'new-password'
$pfxFileByte = $x509Cert.Export($type, $password)

# Write to a file
[System.IO.File]::WriteAllBytes("C:\Temp\certificate.pfx", $pfxFileByte)

Leave a Comment

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