使用 SSL 通过 JDBC 连接到 Google Cloud PostgreSQL

Connection to Google Cloud PostgreSQL via JDBC with SSL

我无法将 Google Cloud PostgreSQL 连接到 JDBC。

Java 版本:1.8.0_162

PostgreSQL JDBC 版本:42.2.2

 try {
    Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
    System.out.println("Class not found");
}

String url = "jdbc:postgresql://ipaddresshere:5432/postgres";

Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","passwordhere");

props.setProperty("ssl","true");
props.setProperty("sslcert","/Users/bguler/Desktop/GoogleCloudPGSSL/client-cert.pem");
props.setProperty("sslkey","/Users/bguler/Desktop/GoogleCloudPGSSL/client-key.pem");
props.setProperty("sslrootcert","/Users/bguler/Desktop/GoogleCloudPGSSL/server-ca.pem");

try {

    Connection conn = DriverManager.getConnection(url, props);
    System.out.println(conn);

} catch (SQLException ex) {

    System.out.println(ex.getMessage());

}

我测试证书路径是正确的。

它抛出一个错误 ;

原因:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径

SSL 错误:sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径

我可以通过 psql 毫无问题地连接到终端;

psql "sslrootcert=server-ca.pem \
  sslcert=client-cert.pem sslkey=client-key.pem \
  hostaddr=ipaddress \
  port=5432 \
  user=postgres dbname=postgres"

Java 使用它自己的密钥存储(而不是 psql 使用的系统存储),它不知道这个特定的证书,因此不信任它。

尝试使用最新版本 Java and/or 查看数据库实例的文档。这应该是一个已知问题。

如果 Postgres 服务器使用的证书不受 Java 默认信任库的信任,您将需要添加它。

首先,将您的证书转换为 DER 格式:

openssl x509 -outform der -in server-ca.pem -out server-ca.der

然后,将其导入密钥库:

keytool -import -trustcacerts -alias your-alias -keystore cacerts -file server-ca.der

或者,您可以使用 Java 系统属性来更改通过添加命令行参数使用的信任库:

-Djavax.net.ssl.trustStore=<path to your trusstore>.jks -Djavax.net.ssl.trustStorePassword=<your password>

通过将以下内容添加到启动命令行,调试 Java SSL 类 也很有帮助:

-Djavax.net.debug=ssl,handshake:verbose