Last active
March 31, 2024 18:25
-
-
Save AfroThundr3007730/3f25f6446bd611257a643ed68c5e6723 to your computer and use it in GitHub Desktop.
Powershell function similar to openssl -s_client to retrieve a certificate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-SSLServerCertificate { | |
<# .SYNOPSIS | |
Retrieves the X509 certificate by connecting to a SSL enabled server #> | |
[Alias('s_client')] | |
Param( | |
# Hostname or IP address to connect to | |
[Parameter(Mandatory)] | |
[String]$Hostname, | |
# Port to connect to | |
[Parameter()] | |
[Int]$Port = 443, | |
# Save cert to file | |
[Parameter()] | |
[switch]$Save, | |
# Don't output base64 | |
[Parameter()] | |
[switch]$Quiet | |
) | |
$client = [Net.Sockets.TcpClient]::new($Hostname, $Port) | |
$sslStream = [Net.Security.SslStream]::new($client.GetStream(), $false, { $true }) | |
$sslStream.AuthenticateAsClient($env:COMPUTERNAME) | |
if ($Save) { | |
[IO.File]::WriteAllBytes( | |
[IO.Path]::Combine($pwd.Path, ( | |
($sslStream.RemoteCertificate.Subject.replace('*', '_') -split ',|=')[1] + '.cer')), | |
$sslStream.RemoteCertificate.GetRawCertData()) | |
} | |
if (!$Quiet) { | |
'-----BEGIN CERTIFICATE-----' | |
[Convert]::ToBase64String( | |
$sslStream.RemoteCertificate.GetRawCertData(), | |
[Base64FormattingOptions]::InsertLineBreaks) | |
'-----END CERTIFICATE-----' | |
} | |
$sslStream.Dispose() | |
$client.Dispose() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With inspiration from https://gist.github.com/IISResetMe/66ab3f0ced4eb406f21bf354cfe7ad45