Class for specifying SSL client certificate via KeyStore - Mailing list pgsql-jdbc

From Brendan Jurd
Subject Class for specifying SSL client certificate via KeyStore
Date
Msg-id CADxJZo1bnEtngocncGVp=S8n2GNa+Z-a6tH9NGcrgWEJoEjXbA@mail.gmail.com
Whole thread Raw
List pgsql-jdbc
Hi there,

For a project of mine, I needed to connect to Postgres using JDBC and
also provide a self-signed SSL certificate for authentication.  I
noticed the following in the jdbc-postgres documentation:

"The Java SSL API is not very well known to the JDBC driver developers
and we would be interested in any interesting and generally useful
extensions that you have implemented using this mechanism.
Specifically it would be nice to be able to provide client
certificates to be validated by the server."

It seems that the most common way to deal with this situation is to
specify the keystore file and the password via system properties
(javax.net.ssl.keyStore et. al.), but that wasn't suitable in my case.
 I needed to be able to load the keystore from a Resource file
embedded in the compiled JAR.

The class I came up with is attached.  It builds on the WrappedFactory
provided in jdbc-postgres.  All the implementer needs to do is
override the two abstract methods to provide an InputStream of the key
store, and the password to access it.  The InputStream could be a
FileInputStream, or an InputStream returned by getResource(), or
whatever.

This class uses the same keystore for KeyManager (selecting the
key/cert to send as the client) and for TrustManager (verifying the
server's certificate against trusted CAs).  It could easily be
extended to allow for two separate keystores by adding another couple
of methods.

There may be a more idiomatically correct way to achieve this -- Java
isn't my native language -- but it does actually work.  I submit it in
the hope that it is useful to somebody.  It seems like a common enough
use-case that if this class, or something like it, were included in
jdbc-postgres it could save some folks some pain.

Cheers,
BJ

Attachment

pgsql-jdbc by date:

Previous
From: xpro6000
Date:
Subject: logging log4j to postgresql
Next
From: Steven Schlansker
Date:
Subject: Extracting more useful information from PSQLException