Spring Boot 配置使用 PEM 格式SSL/TLS证书和私钥

时间:2025-02-24 19:34:31

传统的为 Spring Boot 配置SSL/TLS证书一般都会把证书打包成 JKS(Java KeyStore) 或 PKCS12 (Public Key Cryptographic Standards) 格式,然后为Spring Boot 增加以下类似配置:

# The format used for the keystore. It could be set to JKS in case it is a JKS file
-store-type=PKCS12
# The path to the keystore containing the certificate
-store=classpath:keystore/baeldung.p12
# The password used to generate the certificate
-store-password=xxxxxxx
# The alias mapped to the certificate
-alias=example_com

但很多时候我们拿到的是 PEM (Privacy Enhanced Mail)格式的证书和私钥,比如Nginx配置证书时就是使用的该格式,传统上要把它们应用到 Spring Boot 里需要转换成前述的 JKS 或者 PKCS12 格式,比如:

openssl pkcs12 -inkey ./ -in ./ -export -out ./certificateWithKey.p12

重点是,从 Spring Boot 2. 版本开始,已经增加了对 PEM 格式证书的支持,不需要再做额外的转换,这一点目前还鲜有文档或教程提到,所有这里记录一下

=classpath:
-private-key=classpath:
-certificate=classpath:

具体文档可以查看这里 /spring-boot/docs/current/reference/html/#-files,这样的好处是能实现所有平台和软件的证书在格式上都保持一致。