Skip to content

Instantly share code, notes, and snippets.

@brettmillerb
Last active May 23, 2022 18:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brettmillerb/2fd52047974628f76e46839fe8ace2a5 to your computer and use it in GitHub Desktop.
Save brettmillerb/2fd52047974628f76e46839fe8ace2a5 to your computer and use it in GitHub Desktop.
Export-AzKeyVaultCertficate.ps1
function Export-AzKeyVaultCertificate {
[CmdletBinding()]
param (
[parameter(Mandatory)]
[string]
$VaultName,
[Parameter(Mandatory)]
[string]
$CertName,
$ExportedCertName,
[securestring]
$Credential,
[string]
$ExportPath = $PWD
)
if ($ExportedCertName) {
$outputCertName = $ExportedCertName
}
else {
$outputCertName = $CertName
}
$pfxPath = Join-Path -Path $ExportPath -ChildPath ("{0}.pfx" -f $outputCertName)
$kvCertificate = Get-AzKeyVaultSecret -VaultName $VaultName -SecretName $CertName
if (-not $kvCertificate) {
throw "No Certificate Found in KeyVault."
}
$certBytes = [convert]::FromBase64String(($kvCertificate.SecretValue | ConvertFrom-SecureString -AsPlainText))
$certCollection = [System.Security.Cryptography.X509Certificates.X509Certificate2Collection]::new()
$certCollection.Import(
$certbytes,
$null,
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
)
$password = $Credential | ConvertFrom-SecureString -AsPlainText
$protectedCertBytes = $certCollection.Export(
[System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12,
$password
)
[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertBytes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment