CertPathValidatorException Java尝试使用SSL连接到服务器数据库

时间:2018-10-15 03:35:36

标签: java mysql hibernate ssl google-cloud-sql

我有一个Java应用程序(带有休眠状态),试图在带有Google Cloud SQL + Compute Engine的项目中使用,但没有成功。

Google Cloud SQL要求我使用server-ca.pemclient-cert.pemclient-key.pem通过SSL连接到数据库。

在此之前,我使用属性连接到数据库:

hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost/dbname?autoReconnect=true&useSSL=false
hibernate.connection.username=root
hibernate.connection.password=pass

hibernate.dialect=org.hibernate.dialect.MySQLDialect

如何更改它以使其与SSL配合使用?

谢谢!

[编辑]

尝试了Pooja Aggarwal的答案,但是没有用。

使用-Djavax.net.debug=all时出现异常:

Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors

[编辑2]

我运行的用于生成证书的命令:

openssl pkcs12 -export -in client-cert.pem -inkey client-key.pem \
  -name "mysqldb" -passout pass:MYPASS -out client-keystore.p12


keytool -importkeystore -srckeystore client-keystore.p12 -srcstoretype pkcs12 \
 -srcstorepass MYPASS -destkeystore keystore -deststoretype JKS -deststorepass MYPASS

然后执行:

java -Djavax.net.ssl.keyStore=/home/user/cert/keystore -Djavax.net.ssl.keyStorePassword=MYPASS -jar MyApp.jar

PS: 我可以使用:

 mysql -uroot -p -h 192.00.00.00 \
    --ssl-ca=server-ca.pem --ssl-cert=client-cert.pem \
    --ssl-key=client-key.pem

1 个答案:

答案 0 :(得分:2)

请遵循此链接中提到的步骤。 https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-using-ssl.html

您需要将useSSL标记为true,并在JDK中导入证书,以上链接中提到了其步骤。然后,您需要设置系统属性。

System.setProperty("javax.net.ssl.keyStore","path_to_keystore_file"); 
System.setProperty("javax.net.ssl.keyStorePassword","mypassword");

使用此链接中提到的步骤导入证书:How to import a .cer certificate into a java keystore?