Last active
May 23, 2022 18:20
-
-
Save brettmillerb/2fd52047974628f76e46839fe8ace2a5 to your computer and use it in GitHub Desktop.
Export-AzKeyVaultCertficate.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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