Skip to content

Instantly share code, notes, and snippets.

@mrzachhigginsofficial
Created June 6, 2023 20:45
Show Gist options
  • Save mrzachhigginsofficial/69cda7724415dc2fbee9f991a269c23e to your computer and use it in GitHub Desktop.
Save mrzachhigginsofficial/69cda7724415dc2fbee9f991a269c23e to your computer and use it in GitHub Desktop.
Migrate Azure Key Vault Certificates
# run add-azaccount if login issues
# ----
# If az tools not installed, run:
# Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; rm .\AzureCLI.msi
################################################
$vaultName_old = ''
$subscription_old = ''
$vaultName_new = ''
$subscription_new = ''
$backupDirectory = '' #local directory where pfx will be temp saved
$certPassword = '' #do not save this script with a password
# BACKUP ALL CERTS
Set-AzContext -Subscription $subscription_old
foreach($cert in (Get-AzKeyVaultCertificate -VaultName $vaultName_old))
{
$name = $cert.Name
$certBase64 = Get-AzKeyVaultSecret -VaultName $vaultName -Name $name -AsPlainText
$certBytes = [Convert]::FromBase64String($certBase64)
$x509Cert = New-Object Security.Cryptography.X509Certificates.X509Certificate2
$x509Cert.Import($certBytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxFileByte = $x509Cert.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $certPassword)
$fileName = $backupDirectory +$name+'.pfx'
[IO.File]::WriteAllBytes($fileName, $pfxFileByte)
}
# RESTORE ALL CERTS
Set-AzContext -Subscription $subscription_new
foreach($file in (get-childitem $backupDirectory))
{
$Password = ConvertTo-SecureString -String $certPassword -AsPlainText -Force
$Base64String = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($file.FullName))
Import-AzKeyVaultCertificate -VaultName $vaultName_new -Name ($file.Name.replace('.pfx','')) -CertificateString $Base64String -Password $Password
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment