Configure spring to connect to mysql over ssl

d123 picture d123 · Jan 10, 2013 · Viewed 21k times · Source

I am connecting to MySQL over SSL from my Java application. I have configured MYSQL to support SSL and generated client certificates. I have imported server CA certificate and client certificate into keystore. This is how my code currently looks like

    String url = "jdbc:mysql://127.0.0.1:3306/MySampleDb? verifyServerCertificate =true&useSSL=true&requireSSL=true"

    System.setProperty("javax.net.ssl.keyStore","/home/cert/keystore");
    System.setProperty("javax.net.ssl.keyStorePassword","password");
    System.setProperty("javax.net.ssl.trustStore","/home/cert/truststore");
    System.setProperty("javax.net.ssl.trustStorePassword","password");

    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection(url, user, password);

I want to use spring with C3p0 to connect to MYSQL over SSL.This is my spring configuration file which reads parameters from jdbc.properties.

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    ........
</bean>

How can I configure spring to set properties verifyServerCertificate =true
useSSL=true
requireSSL=true"

Also is it possible to set keyStore and trustStore values in spring config file.

Answer

Marcel St&#246;r picture Marcel Stör · Jan 10, 2013

The value for jdbc.url in jdbc.properties has to be

jdbc:mysql://127.0.0.1:3306/MySampleDb?verifyServerCertificate=true&useSSL=true&requireSSL=true

Those parameters must be added directly to the URL for MySQL. The parameters for keyStore and trustStore should be passed to the JVM at start like so:

-Djavax.net.ssl.keyStore=path_to_keystore_file
-Djavax.net.ssl.keyStorePassword=password
-Djavax.net.ssl.trustStore=path_to_truststore_file
-Djavax.net.ssl.trustStorePassword=password

You can use Spring to set system properties but I'd never use it, it's too cumbersome.