Created
May 17, 2017 20:49
-
-
Save rgl/54d863f9f4edb86c2545c900dc3be0b4 to your computer and use it in GitHub Desktop.
Export a given server certificate chain into local independent files
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
Set-StrictMode -Version Latest | |
$ErrorActionPreference = 'Stop' | |
trap { | |
Write-Output "ERROR: $_" | |
Write-Output (($_.ScriptStackTrace -split '\r?\n') -replace '^(.*)$','ERROR: $1') | |
Write-Output (($_.Exception.ToString() -split '\r?\n') -replace '^(.*)$','ERROR EXCEPTION: $1') | |
Exit 1 | |
} | |
Add-Type @' | |
using System; | |
using System.IO; | |
using System.Linq; | |
using System.Net.Security; | |
using System.Net.Sockets; | |
using System.Security.Authentication; | |
using System.Security.Cryptography.X509Certificates; | |
public class TlsServerCertificateChainExporter | |
{ | |
public static void Export(string serverName, int serverPort) | |
{ | |
var certificatePathPrefix = serverName; | |
Console.WriteLine("Establishing TCP connection to the {0} server...", serverName); | |
using (var client = new TcpClient(serverName, serverPort)) | |
{ | |
Console.WriteLine("Establishing TLS connection..."); | |
using (var sslStream = new SslStream( | |
client.GetStream(), | |
false, | |
(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => | |
{ | |
if (sslPolicyErrors == SslPolicyErrors.None) | |
{ | |
Console.WriteLine("The server certificate validated successfully."); | |
} | |
else | |
{ | |
Console.WriteLine("The server certificate validation failed with the {0} errors.", sslPolicyErrors); | |
} | |
Console.WriteLine("Saving the server certificate chain into separate {0}-*.der files...", certificatePathPrefix); | |
foreach (var elementWithIndex in chain.ChainElements.Cast<X509ChainElement>().Select((e, i) => new { e, i })) | |
{ | |
File.WriteAllBytes( | |
string.Format("{0}-{1}.der", certificatePathPrefix, elementWithIndex.i), | |
elementWithIndex.e.Certificate.Export(X509ContentType.Cert)); | |
} | |
// always allow the connection to go through. | |
return true; | |
}, | |
null)) | |
{ | |
Console.WriteLine("Authenticating the server..."); | |
sslStream.AuthenticateAsClient(serverName); | |
} | |
} | |
} | |
} | |
'@ | |
[TlsServerCertificateChainExporter]::Export('httpbin.org', 443) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment