Created
December 12, 2018 17:41
-
-
Save markscottwright/34a5721933588a03900459f0ff0522bf to your computer and use it in GitHub Desktop.
How to fetch certificates from a TLS connection
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
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.net.UnknownHostException; | |
import java.security.KeyManagementException; | |
import java.security.KeyStore; | |
import java.security.KeyStoreException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.cert.Certificate; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
import javax.net.ssl.SSLContext; | |
import javax.net.ssl.SSLSocket; | |
import javax.net.ssl.TrustManager; | |
import javax.net.ssl.X509TrustManager; | |
public class CertFetcher { | |
private String hostname; | |
private int port; | |
public CertFetcher(String hostname, int port) { | |
this.hostname = hostname; | |
this.port = port; | |
} | |
public X509Certificate[] getCerts() throws UnknownHostException, | |
IOException, | |
NoSuchAlgorithmException, | |
KeyManagementException { | |
SSLContext sslCtx = SSLContext.getInstance("TLS"); | |
sslCtx.init(null, new TrustManager[] { new X509TrustManager() { | |
private X509Certificate[] accepted; | |
@Override | |
public void checkClientTrusted(X509Certificate[] xcs, String string) | |
throws CertificateException { | |
} | |
@Override | |
public void checkServerTrusted(X509Certificate[] xcs, String string) | |
throws CertificateException { | |
accepted = xcs; | |
} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
return accepted; | |
} | |
} }, null); | |
try (SSLSocket s = (SSLSocket) sslCtx.getSocketFactory() | |
.createSocket(hostname, port)) { | |
s.startHandshake(); | |
Certificate[] certs = s.getSession().getPeerCertificates(); | |
X509Certificate[] x509Certs = new X509Certificate[certs.length]; | |
for (int i = 0; i < certs.length; i++) { | |
x509Certs[i] = (X509Certificate) certs[i]; | |
} | |
return x509Certs; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment