常见证书格式

格式 编码 扩展名 说明
PEM Base64 ASCII .pem, .crt, .cer 最常用,文本格式
DER 二进制 .der, .cer Java、Windows 常用
P7B/PKCS#7 Base64 ASCII .p7b, .p7c 仅含证书链,无私钥
PFX/PKCS#12 二进制 .pfx, .p12 含证书和私钥,有密码保护

PEM 与 DER 互转

PEM → DER

1
openssl x509 -in cert.pem -outform DER -out cert.der

DER → PEM

1
openssl x509 -in cert.der -inform DER -out cert.pem

PEM 与 P7B 互转

PEM → P7B

1
openssl crl2pkcs7 -nocrl -certfile cert.pem -out cert.p7b

多个证书(证书链):

1
openssl crl2pkcs7 -nocrl -certfile cert.pem -certfile chain.pem -out full.p7b

P7B → PEM

1
openssl pkcs7 -in cert.p7b -print_certs -out cert.pem

PEM 与 PFX 互转

PEM → PFX(证书 + 私钥打包)

1
openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem

包含证书链:

1
openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem -certfile chain.pem

导出时设置密码(交互式输入):

1
openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem -passout pass:yourpassword

PFX → PEM(解包)

提取所有内容(证书 + 私钥):

1
openssl pkcs12 -in cert.pfx -out cert_and_key.pem -nodes

仅提取证书:

1
openssl pkcs12 -in cert.pfx -clcerts -nokeys -out cert.pem

仅提取私钥:

1
openssl pkcs12 -in cert.pfx -nocerts -nodes -out key.pem

查看文件格式

1
file cert.pem cert.der cert.p7b cert.pfx

输出示例:

1
2
3
4
cert.pem:  PEM certificate
cert.der:  Certificate, Version=3
cert.p7b:  ASCII text
cert.pfx:  data

常见场景

IIS 导入证书(需要 PFX)

1
openssl pkcs12 -export -out iis.pfx -inkey key.pem -in cert.pem -certfile chain.pem

Java KeyStore 导入(需要 DER)

1
2
openssl x509 -in cert.pem -outform DER -out cert.der
keytool -import -alias mycert -file cert.der -keystore my.jks

Nginx/Apache(使用 PEM)

PFX 转 PEM 后直接使用:

1
2
openssl pkcs12 -in cert.pfx -out cert.pem -nodes
# 然后分离证书和私钥

注意事项

  1. PFX 密码:导出时设置的密码在导入时需要
  2. 私钥保护-nodes 表示不加密私钥,生产环境建议移除
  3. 格式识别:不确定格式时用 file 命令查看

参考来源