Skip to content

Instantly share code, notes, and snippets.

@shanehoey
Last active September 10, 2023 10:17
Show Gist options
  • Save shanehoey/925740f09ab07d5be9d527dfb938a9ac to your computer and use it in GitHub Desktop.
Save shanehoey/925740f09ab07d5be9d527dfb938a9ac to your computer and use it in GitHub Desktop.
Self Signed Certificates

New-SelfSignedCert

Create a self signed cert and export to a file

./new-selfsignedcert.ps1 -cn localhost -ip "127.0.0.1"
    #$san,
    #$pfx = ".\cert.pfx"
    #$cer = ".\cert.cer"
    [securestring]$secret,
    [string]$friendlyname="SelfSigned Cert",
    [int]$years=1
[CmdletBinding()]
param (
[Parameter(mandatory=$true)]
[string]$cn,
[Parameter(mandatory=$false)]
[string]$san,
[Parameter(mandatory=$false)]
[string]$ip,
[Parameter(mandatory=$false)]
[string]$pfx = ".\cert.pfx",
[Parameter(mandatory=$false)]
[string]$cer = ".\cert.cer",
[Parameter(mandatory=$true)]
[securestring]$secret,
[Parameter(mandatory=$false)]
[string]$friendlyname="SelfSigned Cert",
[Parameter(mandatory=$false)]
[int]$years=1
)
try {
#Todo: make SAN AND IP an array
$TextExtension = '2.5.29.17={text}dns=' + $($cn) + $(if($san){"&dns=$($san)" }) + $(if($ip){"&IPAddress=$($ip)"})
$cert = New-selfsignedCertificate -FriendlyName "$($friendlyname)" -Subject "cn=$($cn)" -KeyExportPolicy "Exportable" -NotAfter (get-date).AddYears($years) -TextExtension @($TextExtension) -CertStoreLocation "cert:\LocalMachine\My"
$pfxcert = Export-PFXCertificate -Cert $cert -FilePath $pfx -Password $secret
$rootcert = Export-Certificate -Cert $cert -FilePath $cer -Type CER
import-PFXcertificate -FilePath $cer `
-CertStoreLocation Cert:\LocalMachine\Root `
-Password $secret
} catch {
Write-error $_.Exception.Message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment