# PowerShell 脚本:生成自签名证书 # 处理命令行参数 param( [Parameter(HelpMessage="证书有效期(天数)")] [int]$days = 365, [Parameter(HelpMessage="证书主题")] [string]$subject = "CN=localhost,OU=Test,O=GoProxy,L=Shanghai,S=Shanghai,C=CN", [Parameter(HelpMessage="公用名(CN)")] [string]$cn = "", [Parameter(HelpMessage="显示帮助信息")] [switch]$help ) # 帮助信息 function Show-Help { Write-Host "生成自签名证书" Write-Host Write-Host "用法: .\generate_cert.ps1 [选项]" Write-Host Write-Host "选项:" Write-Host " -help 显示此帮助信息" Write-Host " -days DAYS 证书有效期(天数),默认: 365" Write-Host " -subject SUB 证书主题,默认: $subject" Write-Host " -cn CN 公用名(CN),将替换主题中的CN,默认: localhost" Write-Host Write-Host "示例:" Write-Host " .\generate_cert.ps1 -days 730 -cn example.com" Write-Host } # 如果请求帮助,显示帮助信息并退出 if ($help) { Show-Help exit 0 } # 如果指定了CN,替换主题中的CN部分 if ($cn -ne "") { $subject = $subject -replace "CN=[^,]*", "CN=$cn" } Write-Host "生成自签名证书..." Write-Host "有效期: $days 天" Write-Host "主题: $subject" # 检查OpenSSL是否可用 $openssl = Get-Command "openssl" -ErrorAction SilentlyContinue if (-not $openssl) { Write-Host "错误: 未找到OpenSSL命令。请安装OpenSSL并确保它在PATH环境变量中。" -ForegroundColor Red Write-Host "您可以从以下地址下载OpenSSL for Windows: https://slproweb.com/products/Win32OpenSSL.html" -ForegroundColor Yellow exit 1 } try { # 生成私钥 Write-Host "正在生成私钥..." -ForegroundColor Cyan & openssl genrsa -out server.key 2048 # 生成证书请求 Write-Host "正在生成证书请求..." -ForegroundColor Cyan & openssl req -new -key server.key -out server.csr -subj $subject.Replace(",", "/") # 生成自签名证书 Write-Host "正在生成自签名证书..." -ForegroundColor Cyan & openssl x509 -req -days $days -in server.csr -signkey server.key -out server.crt # 删除证书请求文件 Remove-Item server.csr -Force Write-Host "完成!已生成以下文件:" -ForegroundColor Green Write-Host " - server.key: 私钥" -ForegroundColor Green Write-Host " - server.crt: 证书" -ForegroundColor Green Write-Host Write-Host "您可以使用这些文件启动HTTPS代理:" -ForegroundColor Cyan Write-Host "go run cmd/custom_dns_https_proxy/main.go -cert server.crt -key server.key" -ForegroundColor Cyan } catch { Write-Host "错误: 生成证书时发生错误: $_" -ForegroundColor Red exit 1 }