Connecting to MySQL via an Encrypted Connection using SSL and JDBC

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

The MySQL JDBC driver provides support for using SSL when connecting to the MySQL 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 MySQL 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 MySQL database using SSL and JDBC. The useSSL=true property is added to the JDBC URL to attempt to communicate via SSL. The requireSSL=true property can be added to only connect if the database server supports SSL. The verifyServerCerticate=false property is set to bypass certificate validation.

import java.sql.*; public class TestMySQLSSL { public static void main (String[] args) { Connection con = null; try { String url = "jdbc:mysql://"+ "?verifyServerCertificate=false"+ "&useSSL=true"+ "&requireSSL=true"; String user = "testuser"; String password = "testpass"; Class dbDriver = Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, password); } catch (Exception ex) { ex.printStackTrace(); } finally { if (con != null) { try { con.close(); } catch (Exception e){} } } } }