I set the system properties for the MySQL client with SSL support, which worked perfectly:
System.setProperty("javax.net.ssl.trustStore","truststore"); System.setProperty("javax.net.ssl.trustStorePassword","12345"); String url = "jdbc:mysql://abc.com:3306/test?" + "user=abc&password=123" + "&useUnicode=true" + "&characterEncoding=utf8&useSSL=true"
A few days ago, I discovered that a client cannot connect to another website that has a commercially signed SSL certificate installed. Obviously, the main server storages do not work with regular https connections. Then I decided to create my version of SocketFactory based on StandardSocketFactory.java in the MySQL Connector / J source.
I have added the method of creating Socket objects to the public Socket connect method (String hostname, int portNumber, Properties).
private Socket createSSLSocket(InetAddress address, int port) { Socket socket; try { InputStream trustStream = new FileInputStream(new File("truststore")); KeyStore trustStore = KeyStore.getInstance("JKS"); // load the stream to your store trustStore.load(trustStream, trustPassword); // initialize a trust manager factory with the trusted store TrustManagerFactory trustFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); trustFactory.init(trustStore); // get the trust managers from the factory TrustManager[] trustManagers = trustFactory.getTrustManagers(); // initialize an ssl context to use these managers and set as default SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagers, null); if(address == null) { socket = sslContext.getSocketFactory().createSocket(); } else { socket = sslContext.getSocketFactory().createSocket(address, port); } } catch (Exception e) { System.out.println(e.getLocalizedMessage()); return null; } return socket; }
The URL passed to the jdbc driver changes to:
String url = "jdbc:mysql://abc.com:3306/test?" + "user=abc&password=123" + "&useUnicode=true" + "&characterEncoding=utf8&useSSL=true" + "&socketFactory=" + MySocketFactory.class.getName();
The client executed my version of createSSLSocket () and returned a Socket object. However, after continuing execution, I received the following Exceptions:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I am sure that MySQL is up and running, the address and port passed to createSSLSocket () were correct. Can anyone help? The client must simultaneously communicate with two sites: the HTTPS web server and the self-signed MySQL server.