Last active
July 14, 2024 15:53
-
-
Save indented-automation/cda156b3d456c2d7aece7a4451784e0d to your computer and use it in GitHub Desktop.
Save-WebCertificate
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 Save-WebCertificate { | |
param ( | |
# Attempt to acquire a certificate from the specified URI | |
[Parameter(Mandatory)] | |
[ValidateScript( { $_.Scheme -eq 'https' } )] | |
[Uri]$Uri, | |
# Save the certificate in PEM format to the specified path. | |
[Parameter(Mandatory)] | |
[String]$Path, | |
# Return the certificate object to the output pipeline. | |
[Switch]$PassThru | |
) | |
try { | |
$Path = $pscmdlet.GetUnresolvedProviderPathFromPSPath($Path) | |
$tcpClient = [System.Net.Sockets.TcpClient]::new() | |
$tcpClient.Connect($Uri.Host, $Uri.Port) | |
$sslStream = [System.Net.Security.SslStream]::new( | |
$tcpClient.GetStream(), | |
$false, | |
{ return $true }, | |
$null | |
) | |
$sslStream.AuthenticateAsClient($Uri.Host) | |
# ToBase64String options allows a 76-character break with the InsertLineBreaks option. | |
# Make the split 64-characters to exactly match openssl. | |
$pemString = @( | |
'-----BEGIN CERTIFICATE-----' | |
[Convert]::ToBase64String( | |
$sslStream.RemoteCertificate.Export('Cert') | |
) -split '(?<=\G.{64})' | |
'-----END CERTIFICATE-----', | |
'' | |
) -join "`n" | |
[System.IO.File]::WriteAllText($Path, $pemString.ToString()) | |
if ($PassThru) { | |
[System.Security.Cryptography.X509Certificates.X509Certificate2]$sslStream.RemoteCertificate | |
} | |
} catch { | |
throw | |
} finally { | |
if ($tcpClient.Connected) { | |
$tcpClient.Close() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment