Skip to content

Instantly share code, notes, and snippets.

@EinPinsel
Created December 19, 2019 20:53
Show Gist options
  • Save EinPinsel/c2857b59f7042f74f6a88fc68bad694c to your computer and use it in GitHub Desktop.
Save EinPinsel/c2857b59f7042f74f6a88fc68bad694c to your computer and use it in GitHub Desktop.
Get-Certificate in base64 format
function Get-CertChain {
param (
[string]$computername,
[int]$port = 443
)
#Create a TCP Socket to the computer and a port number
$tcpsocket = New-Object Net.Sockets.TcpClient($computerName, $port)
#test if the socket got connected
if (!$tcpsocket) {
Write-Error "Error Opening Connection: $port on $computername Unreachable"
exit 1
}
else {
#Socket Got connected get the tcp stream ready to read the certificate
Write-Host "Successfully Connected to $computername on $port" -ForegroundColor Green -BackgroundColor Black
$tcpstream = $tcpsocket.GetStream()
Write-Host "Reading SSL Certificate...." -ForegroundColor Yellow -BackgroundColor Black
#Create an SSL Connection
$sslStream = New-Object System.Net.Security.SslStream($tcpstream, $false)
#Force the SSL Connection to send us the certificate
$sslStream.AuthenticateAsClient($computerName)
#Read the certificate
$certinfo = New-Object system.security.cryptography.x509certificates.x509certificate2($sslStream.RemoteCertificate)
# Use the Cert Info to get the Certificate itself converted into Base64
$Base64Cert = [convert]::ToBase64String(($certinfo).RawData, 'InsertLineBreaks')
$output =
@"
-----BEGIN CERTIFICATE-----
$Base64Cert
-----END CERTIFICATE-----
"@
}
return $output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment