Proxy/OpenSSL.ps1

<#
.SYNOPSIS
    Finds the OpenSSL start.bat script in Program Files.
#>

function Find-OpenSSLStartScript {
    [CmdletBinding()]
    param()

    $results = @()
    $opensslDirs = Get-ChildItem -Path "$env:ProgramFiles\OpenSSL*" -Directory -ErrorAction SilentlyContinue
    foreach ($dir in $opensslDirs) {
        $batPath = Join-Path -Path $dir.FullName -ChildPath 'start.bat'
        if (Test-Path $batPath) {
            $results += $batPath
        }
    }

    if ($results.Count -gt 0) {
        return $results
    }
    else {
        Write-Verbose 'OpenSSL start script (start.bat) not found.'
        return @()
    }
}

<#
.SYNOPSIS
    Creates a self-signed certificate and private key using OpenSSL on Windows.
#>

function New-SelfSignedCertWithOpenSSL {
    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(Mandatory=$true)]
        [string] $Subject,
        
        [Parameter(Mandatory=$false)]
        [string] $OutputDir = (Get-Location).Path,
        
        [Parameter(Mandatory=$false)]
        [int] $Days = 365,
        
        [Parameter(Mandatory=$true)]
        [string] $OpenSSLPath
    )

    if (-not (Test-Path $OpenSSLPath)) {
        Throw "openssl.exe not found at path: $OpenSSLPath"
    }

    if (-not (Test-Path $OutputDir)) {
        if ($PSCmdlet.ShouldProcess($OutputDir, "Create directory for certificates")) {
            New-Item -Path $OutputDir -ItemType Directory | Out-Null
        }
    }

    $keyFile  = Join-Path $OutputDir 'private.key'
    $certFile = Join-Path $OutputDir 'certificate.crt'

    $opensslArgs = @('req', '-x509', '-newkey', 'rsa:2048', '-nodes',
                     '-keyout', "`"$keyFile`"", '-out', "`"$certFile`"",
                     '-days', $Days.ToString(), '-subj', "`"$Subject`"")

    if ($PSCmdlet.ShouldProcess($OpenSSLPath, "Generate self-signed certificate")) {
        $proc = Start-Process -FilePath $OpenSSLPath -ArgumentList $opensslArgs -NoNewWindow -Wait -PassThru
        if ($proc.ExitCode -ne 0) {
            Throw "OpenSSL returned an error (exit code: $($proc.ExitCode))"
        }
        Write-Host "Self-signed certificate created successfully:" -ForegroundColor Green
        Write-Host " - Private Key: $keyFile"
        Write-Host " - Certificate: $certFile"
        Write-Host " - Expires in: $Days days"
    }
}