MySQL jdbc + SSL

问题描述 投票:0回答:1

我为启用 SSL 的 MySQL 客户端设置系统属性,效果很好:

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"

几天前,我发现客户端无法连接到另一个安装了商业签名 SSL 证书的网站。显然,覆盖的密钥库不适用于常规 https 连接。 然后我决定基于 MySQL Connector/J 源中的 StandardSocketFactory.java 构建我的 SocketFactory 版本。

我在 public Socket connect(String hostname, int portNumber, Properties props) 方法中添加了一个创建 Socket 对象的方法。

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;
}

传递给jdbc驱动程序的url更改为:

    String url = "jdbc:mysql://abc.com:3306/test?" +
             "user=abc&password=123" +
             "&useUnicode=true" +
             "&characterEncoding=utf8&useSSL=true" +
             "&socketFactory=" + MySocketFactory.class.getName();

客户端确实执行了我的版本createSSLSocket()并返回了一个Socket对象。然而,继续执行后出现以下异常:

    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?

我确定 MySQL 已启动并正在运行,传递给 createSSLSocket() 的地址和端口是正确的。有人可以帮忙吗?客户端必须同时与 2 个站点通信:一个 HTTPS Web 服务器和一个自签名 MySQL 服务器。

java mysql sockets ssl jdbc
1个回答
-1
投票

我也面临着类似的问题。您可以在这里发布您的修复吗

© www.soinside.com 2019 - 2024. All rights reserved.