Skip to content

Instantly share code, notes, and snippets.

@tmeckel
Last active June 2, 2019 16:01
Show Gist options
  • Save tmeckel/2ebd96e03969e2b6e5922887b3f978a8 to your computer and use it in GitHub Desktop.
Save tmeckel/2ebd96e03969e2b6e5922887b3f978a8 to your computer and use it in GitHub Desktop.
Windows: Create new Server Certificate

Create a new Server Certificate

Prerequisite: https://github.com/FiloSottile/mkcert

$env:CAROOT = Join-Path $PSScriptRoot 'CA'
<#
mkcert creates the directory if it does not exist

if (-not (Test-Path $env:CAROOT)) {
    New-Item -ItemType Directory -Path $env:CAROOT -ErrorAction:Stop
}
#>
$cmdMkCert = Join-Path -Path $PSScriptRoot -ChildPath "mkcert*" -Resolve -ErrorAction:Stop
$ipProps = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
$authList = [System.Collections.ArrayList]@(
    $ipProps.HostName
) 
if ($ipProps.DomainName) {
    $authList += "*.$($ipProps.DomainName)"
}
$authList.Add(([System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() `
    | %{ $_.GetIPProperties().UnicastAddresses.Address.IPAddressToString } `
    | ?{ $_ -notlike '*%*' }))

$argv = @(
    '-pkcs12' # The generated pkcs file will match '$Hostname+<NumberOfHostnamesAsideHostname>.p12'
)
$argv += $authList

& $cmdMkCert @argv

& $cmdMkCert -install

$password = ConvertTo-SecureString -AsPlainText -String 'changeit' -Force
Get-ChildItem -Path $PSScriptRoot `
    | Where-Object { $_.Name -match "$($ipProps.HostName)\+[0-9]+\.p12" } `
    | ForEach-Object {
        Import-PfxCertificate `
            -Exportable `
            -Password $password `
            -FilePath $_.FullName `
            -CertStoreLocation Cert:\LocalMachine\My
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment