April 26, 2011

Secure JDBC connection to MySQL from Java


Connecting to a database with JDBC is easy but gets a little more complicated if a secure connection is needed.  This is how a secure connection to MySQL is established using keystore/truststore SSL keys.  Overall, nothing too spectacular here but a useful reference.


The Java code to get a secure JDBC connection to MySQL is easy.  It is a matter of adding properties to the URL connection string which inform the MySQL JDBC driver to use a secure connection.

  String username = "[USERNAME]";
  String password = "[PASSWORD]";

  StringBuilder url = new StringBuilder();


  Connection conn = DriverManager.getConnection(url.toString(), username, password);

System Properties

The properties on the URL connection string tell the MySQL JDBC driver to use a secure connection but you still need to tell your application where the keystore/truststore SSL keys are located.  Do this using the following system properties when you start the JVM.


These files will of course need the the keys off your MySQL server.

No comments:

Post a Comment