首页 文章

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

提问于
浏览
0

我无法将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"

2 回答

  • 0

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

    首先,以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 System属性更改添加命令行参数所使用的信任存储:

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

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

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

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

    尝试使用最新版本的Java和/或检查数据库实例的文档 . 这应该是一个已知的问题 .

相关问题