小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot【问题 05】PostgreSQL数据库启用SSL后使用默认配置进行数据库连接(Navicat工具与Java程序)

行业知识

SpringBoot【问题 05】PostgreSQL数据库启用SSL后使用默认配置进行数据库连接(Navicat工具与Java程序)

2026-12-04 00:33:43 来源:互联网转载

官���SSL说明:https://www.postgresql.org/docs/9.1/libpq-ssl.html

1.配置

1.1 文件

使用SSL需要的4个文件,名称要一致:

  1. 客户端密钥:postgresql.key
  2. Java客户端密钥:postgresql.pk8
  3. 客户端证书:postgresql.crt
  4. 根证书:root.crt

1.2 目录

  • Linux
    FileContentsEffect
    ~/.postgresql/postgresql.crtclient certificaterequested by server
    ~/.postgresql/postgresql.keyclient private keyproves client certificate sent by owner; does not indicate certificate owner is trustworthy
    ~/.postgresql/root.crttrusted certificate authoritieschecks that server certificate is signed by a trusted certificate authority
    ~/.postgresql/root.crlcertificates revoked by certificate authoritiesserver certificate must not be on this list
    • Windows

      %APPDATA%\postgresql\实例:C:\Users\Administrator\AppData\Roaming\postgresql

      2.测试

      2.1 Navicat工具(Windows)

      • 使用SSL 模式选择 require或verify-ca都可以
      • C:\Users\Administrator\AppData\Roaming\postgresql下放置postgresql.key postgresql.crt root.crt3个文件

        测试:

        2.2 SpringBoot项目(Linux)

        在使用 Spring Boot 连接 PostgreSQL 数据库时,如果需要使用 SSL 连接,那么私钥(sslkey)应该是 PKCS8 格式。可以使用 OpenSSL 工具将私钥转换为这种格式。来自StackOverflow的解决方案原文https://stackoverflow.com/questions/54257758/spring-boot-connection-to-postgresql-with-ssl。以下是具体的命令:

        openssl pkcs8 -topk8 -inform PEM -outform DER -in postgresql.key -out postgresql.pk8 -nocrypt

        未使用默认路径的自定义配置:

        driver-class-name: org.postgresql.Driverurl: jdbc:postgresql://localhost:25432/dbname?ssl=true&sslrootcert=pathTo/root.crt&sslcert=pathTo/postgresql.crt&sslkey=pathTo/postgresql.pk8username: 'username'password: 'password'

        使用默认路径的配置:

        driver-class-name: org.postgresql.Driverurl: jdbc:postgresql://localhost:25432/dbname?sslmode=requireusername: 'username'password: 'password'

        使用默认路径配置时:

        • sslmode为require或verify-ca都可以
        • ~/.postgresql下放置postgresql.pk8 postgresql.crt root.crt3个文件
          1. 测试 sslmode=require
          # 目录下没有文件时[FATAL: connection requires a valid client certificate]# 添加root.crt后[FATAL: connection requires a valid client certificate]# 添加postgresql.crt后[SSL error: Received fatal alert: unexpected_message]# 添加postgresql.pk8# 正常访问
          1. 测试 sslmode=verify-ca
          # 目录下没有文件时[Could not open SSL root certificate file C:\Users\Administrator\AppData\Roaming\postgresql\root.crt.]# 添加root.crt后[FATAL: connection requires a valid client certificate]# 添加postgresql.crt后[SSL error: Received fatal alert: unexpected_message]# 添加postgresql.pk8# 正常访问

          3.总结

          • 使用默认配置要注意文件路径和文件名称
          • 其他应用程序要注意文件的权限
            # 文件权限错误导致的连接失败# 数据库连接失败:Could not open SSL root certificate file ~./postgresql/root.crt.

上一篇:服务器电脑怎么更换网络?

下一篇:如何停掉腾讯云服务器