Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Last active March 31, 2024 18:25
Show Gist options
  • Save AfroThundr3007730/3f25f6446bd611257a643ed68c5e6723 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/3f25f6446bd611257a643ed68c5e6723 to your computer and use it in GitHub Desktop.
Powershell function similar to openssl -s_client to retrieve a certificate
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()
}
@AfroThundr3007730
Copy link
Author

@AfroThundr3007730
Copy link
Author

Updated version available in my HelperFunctions module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment