Last active
March 4, 2024 18:39
-
-
Save realslacker/0d7f2c8f4afd7c13487cd5c45db90cb1 to your computer and use it in GitHub Desktop.
Return the server certificate a server is using on a specified port
This file contains 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
<# | |
.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