Skip to content

Instantly share code, notes, and snippets.

@cgorshing
Created January 13, 2023 17:44
Show Gist options
  • Save cgorshing/10b3ae516c18b5db5734067e8b9b4cf8 to your computer and use it in GitHub Desktop.
Save cgorshing/10b3ae516c18b5db5734067e8b9b4cf8 to your computer and use it in GitHub Desktop.
Powershell - Trusting a Specific Server Certificate
# https://gist.github.com/runtooctober/d810071e5efc90f7f0927c5669c72153
# https://gist.github.com/bender-the-greatest/26e758cd1ad7b8ae87c688301cac697e
# https://stackoverflow.com/questions/13732826/convert-pem-to-crt-and-key
# https://github.com/PowerShell/PowerShell/issues/7092 --- Reference for a new approach in more recent versions of .NET (not applicable, yet, to me)
$url = "https://your-url-to-hit/some/path"
# This helps get information about the server certificate returned
# $StackExAPIResponse = Invoke-WebRequest $url -TimeoutSec 3 -ErrorAction Stop
# $servicePoint = [System.Net.ServicePointManager]::FindServicePoint("https://your-url-to-hit")
# $servicePoint.Certificate.GetCertHashString()
# $servicePoint.Certificate.GetExpirationDateString()
# $servicePoint.Certificate.ToString($true)
# $servicePoint.Certificate.Issuer
# $servicePoint.Certificate.Subject
# Or
# Invoke-RestMethod -Uri $url -Method Get | Out-Null
# $certificate = ([System.Net.Webrequest]::Create($url)).ServicePoint.Certificate
# $certificate.ToString($true)
using namespace System.Net
using namespace System.Security.Cryptography.X509Certificates
using namespace System.Management.Automation
class TrustAllCertsPolicy : ICertificatePolicy {
[bool] CheckValidationResult (
[ServicePoint]$srvPoint,
[X509Certificate]$certificate,
[WebRequest]$request,
[int]$certificateProblem
) {
return (
$certificate.GetCertHashString() -eq "61E1BEBE8E4C2C12C52A67598D44FAAE16A37F11" -and
$certificate.Issuer -eq '<output from the cli>' -and
$certificate.Subject -eq '<output form the cli>'
)
}
}
[ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12
# $headers = @{"api-token"="1234567890"}
# $request = Invoke-WebRequest -Uri $url -Headers $headers -Method Get -ContentType "Application/Json"
$request = Invoke-WebRequest -UseBasicParsing -Uri $url
Write-Output $request.StatusCode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment