Created
May 13, 2021 13:29
-
-
Save JohnLBevan/ce3b7389bce14bcffe2aa6a46c89500b to your computer and use it in GitHub Desktop.
A wrapper for creating and exporting self-signed certs as PFX files. Useful if setting up sites which require HTTPS config ahead of getting a proper cert (e.g. to configure HTTPS for app gateway before configuring LetsEncrypt per https://intelequia.com/blog/post/1012/automating-azure-application-gateway-ssl-certificate-renewals-with-let-s-encryp…
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
Function New-SelfSignedCertPfx { | |
[CmdletBinding(DefaultParameterSetName = 'PasswordAsSecureString')] | |
Param ( | |
[Parameter()] | |
[string[]]$SanList = @('localhost', '127.0.0.1') | |
, | |
[Parameter(ParameterSetName = 'PasswordAsSecureString')] | |
[SecureString]$ExportPassword = [System.Security.SecureString]::new() | |
, | |
# note: using the secure string option is recommended... but tbh most real world cases where you'd use this script you're just looking for something quick and easy | |
[Parameter(ParameterSetName = 'PasswordAsString', Mandatory)] | |
[string]$PlaintextExportPassword | |
, | |
[Parameter()] | |
[string]$CertStorePath = 'cert:\localmachine\my' | |
, | |
[Parameter()] | |
[string]$PfxOutputPath = '.\selfSignedCert.pfx' | |
, | |
[Parameter()] | |
[DateTime]$DateTo = (Get-Date).ToUniversalTime().AddYears(1) | |
, | |
[Parameter()] | |
[Int32]$KeyLength = 2048 | |
, | |
[Parameter()] | |
[Switch]$KeepInKeyStore | |
) | |
if ($PSCmdlet.ParameterSetName -eq 'PasswordAsString') { | |
$ExportPassword = $PlaintextExportPassword | ConvertTo-SecureString -AsPlainText -Force | |
} | |
[HashTable]$splat = @{ | |
DnsName = $SanList | |
CertStoreLocation = $CertStorePath | |
NotAfter = $DateTo | |
KeyLength = $KeyLength | |
} | |
[System.Security.Cryptography.X509Certificates.X509Certificate2]$tempCert = New-SelfSignedCertificate @splat | |
Export-PfxCertificate -Cert $tempCert -FilePath $PfxOutputPath -Password $ExportPassword | Out-Null | |
if (!$KeepInKeyStore.IsPresent) { | |
Remove-Item -Path $tempCert.PSPath | |
} | |
return ([PSCustomObject]@{ | |
Path = $PfxOutputPath | |
SanList = $SanList | |
ExportPassword = $ExportPassword | |
Certificate = $tempCert | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment