Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active June 23, 2023 16:56
Show Gist options
  • Save indented-automation/cda156b3d456c2d7aece7a4451784e0d to your computer and use it in GitHub Desktop.
Save indented-automation/cda156b3d456c2d7aece7a4451784e0d to your computer and use it in GitHub Desktop.
Save-WebCertificate
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