Connecting to PostgreSQL via an Encrypted Connection using SSL and JDBC

There are instances when it is necessary to connect to a PostgreSQL database containing sensitive information. In these cases, it may be required that any information going out over the public network is encrypted. Assuming the PostgreSQL database has been configured to support SSL, it is quite easy to communicate securely with the PostgreSQL database using SSL and JDBC.

The PostgreSQL JDBC driver provides support for using SSL when connecting to the PostgreSQL database server as long as the database is configured to support SSL. Communicating via SSL can be accomplished by simply passing a connection propery in the JDBC URL. The PostgreSQL JDBC driver also provides an option for bypassing certificate validation. This is useful in cases where a self-signed certificate is being used.

Listed below is a code example showing how to communicate with a PostgreSQL database using SSL and JDBC. The ssl=true property is added to the JDBC URL to communicate via SSL. The sslfactory property is set to the value of org.postgresql.ssl.NonValidatingFactory to bypass certificate validation.

import java.sql.*; public class TestPostgreSQLSSL { public static void main (String[] args) { Connection con = null; try { String url = "jdbc:postgresql://127.0.0.1:5432/sample?"+ "ssl=true&"+ "sslfactory=org.postgresql.ssl.NonValidatingFactory"; String user = "testuser"; String password = "testpass"; Class dbDriver = Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection(url, user, password); } catch (Exception ex) { ex.printStackTrace(); } finally { if (con != null) { try { con.close(); } catch (Exception e){} } } } }