Skip to content

Instantly share code, notes, and snippets.

@LivingGhost
Created February 1, 2021 00:34
Show Gist options
  • Save LivingGhost/fd32943e923c15a06cb8f14e185cc140 to your computer and use it in GitHub Desktop.
Save LivingGhost/fd32943e923c15a06cb8f14e185cc140 to your computer and use it in GitHub Desktop.
自己証明書生成(要管理者権限)
@(echo '> NUL
echo off)
setlocal enableextensions
echo *注意1:自己署名証明書生成には管理者権限が要求されます*
echo *注意2:証明書ファイル(cert.txt)はデスクトップ上の『cert』フォルダへ出力されます*
if "%~1" neq "RESTARTED" ( goto RESTART )
set "THIS_PATH=%~f0"
set "PARAM_1=%~2"
PowerShell.exe -Command "iex -Command ((gc \"%THIS_PATH:`=``%\") -join \"`n\")"
exit /b %errorlevel%
:RESTART
powershell -NoProfile -ExecutionPolicy unrestricted -Command "Start-Process \"%~f0\" -ArgumentList \"RESTARTED %~1\" -WindowStyle Hidden -Verb runas"
exit
') | sv -Name TempVar
# DNS名
$DnsName = "localhost"
# 証明書期限
$expiryDate = "9999-12-31 23:59:59.99999"
# PKCS#12証明書ファイルのパスワード
$password = "password"
# 証明書物理ファイル出力先
$outputDir = [Environment]::GetFolderPath("Desktop") + "\cert"
# 証明書発行
$cert = New-SelfSignedCertificate `
-DnsName $DnsName `
-CertStoreLocation "cert:\LocalMachine\My" `
-KeyDescription "Self-signed certificate" `
-notafter $expiryDate `
-Type SSLServerAuthentication `
-KeyExportPolicy Exportable
# 証明書出力先フォルダ作成
New-Item $outputDir\ -ItemType Directory 2>&1>$null
# export the public key to a file
Export-Certificate -Cert $cert -FilePath $outputDir\publickey.cer
# export the private key to a file with password protection
$pwd = ConvertTo-SecureString -String $password -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath $outputDir\privatekey.pfx -password $pwd
# export the public key a base 64 encoded file
$content = @(
'-----BEGIN CERTIFICATE-----'
[System.Convert]::ToBase64String($cert.RawData, 'InsertLineBreaks')
'-----END CERTIFICATE-----'
)
$content | Out-File -FilePath $outputDir\cert.txt -Encoding ascii
# Windows 証明書ストアから証明書を削除
Remove-Item $cert.PSPath 2>&1>$null
# 証明書出力先フォルダ展開
Invoke-Item $outputDir\ 2>&1>$null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment