Tuesday, November 25, 2008

Reading SSL certificates from a given url

This code explains how you could read and retrieve an X.509 certificate from a given url.

import java.net.URL;
import java.security.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public static Certificate readSSLCertFromUrl(String url) throws Exception {
URL hostURL = null;
String hostname = null;
int port;
SSLSocketFactory factory = null;
SSLSocket socket = null;

try {
hostURL = new URL(url);
hostname = hostURL.getHost();

// Check whether the url has a port stated explicitly. If its not present default to 443
port = hostURL.getPort();
if (port == -1) {
port = 443;

// Gets the default static SSLSocketFactory that is inherited by new instances of this
// class.
// The socket factories are used when creating sockets for secure https URL connections.
factory = HttpsURLConnection.getDefaultSSLSocketFactory();

// Creates a socket and connects it to the specified remote host at the specified remote
// port. This socket is configured using the socket options established for this
// factory.
socket = (SSLSocket) factory.createSocket(hostname, port);

// Starts an SSL handshake on this connection. Common reasons include a need to use new
// encryption keys, to change cipher suites, or to initiate a new session. To force
// complete reauthentication, the current session could be invalidated before starting
// this handshake.

// Retrieve the server's certificate chain
Certificate[] serverCerts = socket.getSession().getPeerCertificates();

// The local certificate first followed by any certificate authorities.
if (serverCerts != null && serverCerts.length > 0) {
return serverCerts[0];
} else {
return null;

} finally {
// Close the socket
if (socket != null) {


Mr. pataTux said...

Can you give to us an example of use, or can you help me with the implementation on a servlet i'm new in this. Thanks a lot.

Prabath said...

There can be cases I want to say a certain Identity Provider to trust a given Relying Party web site. In that case I need to upload relying party web site's certificate to the Identity Provider manually. The other option is simply give the Relying Party web site's URL - so Identity Provider will read it from the URL.