Skip to content

Instantly share code, notes, and snippets.

@jabez007
Created February 12, 2018 15:05
Show Gist options
  • Save jabez007/7d053b3ba51d019339729a3dfd1889d6 to your computer and use it in GitHub Desktop.
Save jabez007/7d053b3ba51d019339729a3dfd1889d6 to your computer and use it in GitHub Desktop.
A PowerShell script for retrieving public certificates from remote websites.
function Get-PublicKey
{
# https://stackoverflow.com/questions/22233702/how-to-download-the-ssl-certificate-from-a-website-using-powershell
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate])]
PARAM (
[Uri]$Uri
)
if (-Not ($uri.Scheme -eq "https"))
{
Write-Error "You can only get keys for https addresses"
return
}
$request = [System.Net.HttpWebRequest]::Create($uri)
try
{
#Make the request but ignore (dispose it) the response, since we only care about the service point
$request.GetResponse().Dispose()
}
catch [System.Net.WebException]
{
if ($_.Exception.Status -eq [System.Net.WebExceptionStatus]::TrustFailure)
{
#We ignore trust failures, since we only want the certificate, and the service point is still populated at this point
}
else
{
#Let other exceptions bubble up, or write-error the exception and return from this method
throw
}
}
#The ServicePoint object should now contain the Certificate for the site.
$servicePoint = $request.ServicePoint
$certificate = $servicePoint.Certificate
Return $certificate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment