Skip to content

Instantly share code, notes, and snippets.

@realslacker
Last active March 4, 2024 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realslacker/0d7f2c8f4afd7c13487cd5c45db90cb1 to your computer and use it in GitHub Desktop.
Save realslacker/0d7f2c8f4afd7c13487cd5c45db90cb1 to your computer and use it in GitHub Desktop.
Return the server certificate a server is using on a specified port
<#
.SYNOPSIS
Return the server certificate a server is using on a specified port
.PARAMETER ComputerName
The remote computer to query
.PARAMETER Port
The remote TCP port to query
.PARAMETER SubjectNameIdentifier
The Subject Name Identifier to send to the server, defaults to the computer name
.PARAMETER SkipCertificateCheck
Bypass certificate trust checking
#>
[CmdletBinding()]
[OutputType( [System.Security.Cryptography.X509Certificates.X509Certificate2] )]
param(
[Parameter( Mandatory, Position = 1 )]
[string]
$ComputerName,
[uint]
$Port = '443',
[string]
$SubjectNameIdentifier,
[switch]
$SkipCertificateCheck
)
#Requires -Version 7.1
try {
$TcpClient = [System.Net.Sockets.TcpClient]::new( $ComputerName, $Port )
$SslStream = [System.Net.Security.SslStream]::new( $TcpClient.GetStream(), $false, ( $SkipCertificateCheck ? {$true} : $null ) )
$SslStream.AuthenticateAsClient(( $SubjectNameIdentifier ?? $ComputerName ))
$SslStream.RemoteCertificate -as [System.Security.Cryptography.X509Certificates.X509Certificate2]
} catch {
throw $_.Exception.Message
} finally {
${SslStream}?.Close()
${TcpClient}?.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment