Skip to content

Instantly share code, notes, and snippets.

@JPRuskin
Created March 5, 2020 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPRuskin/1e7451159a7440440bb8caabc8e56c13 to your computer and use it in GitHub Desktop.
Save JPRuskin/1e7451159a7440440bb8caabc8e56c13 to your computer and use it in GitHub Desktop.
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