Created
March 5, 2020 13:29
-
-
Save JPRuskin/1e7451159a7440440bb8caabc8e56c13 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using namespace Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters | |
function Export-PfxFromAzureKeyVault { | |
<# | |
.Synopsis | |
Exports a PFX file from an Azure KeyVault Certificate | |
.Example | |
Export-PfxFromAzureKeyVault -VaultName TestVault -Name TestCert -Password $SecurePW -Path C:\Temp\TestCert.pfx | |
#> | |
[CmdletBinding()] | |
param( | |
# Name of the KeyVault | |
[ResourceNameCompleter("Microsoft.Keyvault/vaults", "ResourceGroupName")] | |
[Parameter(Mandatory, ValueFromPipelineByPropertyName)] | |
[string]$VaultName, | |
# Name of the Certificate | |
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline)] | |
[string]$Name, | |
# Password to store the PFX with | |
[securestring]$Password, | |
# Path to store the PFX | |
[Parameter(Mandatory)] | |
#[ValidateScript({ | |
#(Test-Path $_ -PathType Container) -or -not ((Test-Path $_ -PathType Leaf) -or $Force) | |
#})] | |
[string]$Path, | |
# Allows clobbering of the cert | |
[switch]$Force | |
) | |
process { | |
if (-not ($Certificate = Get-AzKeyVaultSecret -VaultName $VaultName -Name $CertificateName)) { | |
Write-Error "Certificate '$($Name)' does not exist in '$($VaultName)'" -ErrorAction Stop | |
} | |
$Pfx = [Security.Cryptography.X509Certificates.X509Certificate2]::new( | |
[Convert]::FromBase64String($Certificate.SecretValueText), | |
$null, | |
[Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable | |
) | |
$PfxProtectedBytes = $Pfx.Export( | |
[Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, | |
$Password | |
) | |
$Pfx = $null | |
if ($Path | |
[IO.File]::WriteAllBytes($Path, $PfxProtectedBytes) | |
Get-Item $Path | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment