Skip to content

Instantly share code, notes, and snippets.

@lmoxiel
Created June 11, 2020 13:46
Show Gist options
  • Save lmoxiel/9ea72fca546b16c67484857343b056f3 to your computer and use it in GitHub Desktop.
Save lmoxiel/9ea72fca546b16c67484857343b056f3 to your computer and use it in GitHub Desktop.
This code accesses a Key Vault certificate and certificate password and creates a new exported certificate based on a certificate password which is also stored in Key Vault
# Christopher Jackson (@azurejackson; @ethicaljeans)
# May, 2020
#
# This code accesses a Key Vault certificate and certificate password and creates a new
# exported certificate based a certificate password which is also stored in Key Vault
#
# export-certificate-with-password.ps1
Connect-AzAccount
# Uncomment the below line to explicitly set the correct subscription
# Set-AzContext -SubscriptionId <subscription id>
# Initialize variables
$keyVaultName = "<key vault name>"
$keyVaultCertName = "<key vault certificate name>"
$keyVaultCertPasswordName = "<key vault password name>"
$exportedCertPath = "<absolute/path/to/exported-cert.pfx>"
# Access the Certificate and Certificate password from Key Vault
$keyVaultCert = Get-AzKeyVaultSecret -VaultName $keyVaultName -SecretName $keyVaultCertName
Write-Host -ForegroundColor Yellow "Retrieved Key Vault Certificate..."
$certPassword = Get-AzKeyVaultSecret -VaultName $keyVaultName -SecretName $keyVaultCertPasswordName
Write-Host -ForegroundColor Yellow "Retrieved Key Vault Certificate Password..."
# Create a new PFX object with the data from the downloaded Key Vault Cert
$keyVaultRawBytes = [Convert]::FromBase64String($keyVaultCert.SecretValueText)
$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2($keyVaultRawBytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
Write-Host -ForegroundColor Yellow "Created new PFX certificate..."
$exportedPfx = $pfx.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $certPassword.SecretValue)
Write-Host -ForegroundColor Yellow "Exportable PFX created with Certificate Password"
# Output the new password protected Cert to the filesystem
[IO.File]::WriteAllBytes($exportedCertPath, $exportedPfx)
Write-Host -ForegroundColor Yellow "Certificate Successfully exported to: $exportedCertPath"
# Option: Installing the cert locally and removing the pfx cert file from disk
#Import-PfxCertificate -FilePath $exportedCertPath -CertStoreLocation Cert:\CurrentUser\My -Password $certPassword.SecretValue
#Write-Host -ForegroundColor Yellow "Certificate installation complete."
#Remove-Item -Path $exportedCertPath -Force
#Write-Host -ForegroundColor Yellow "Certificate at location '$exportedCertPath' deleted."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment