如何将 pem 文件转换为 pfx 文件?

How do I convert a pem to pfx file?

This has me confused:

Convert pfx to PEM:
openssl pkcs12 -in certificatename.pfx -out certificatename.pem

这样做会转储出一个单个纯文本文件。

现在如何将此纯文本 pem 转换回 pfx?

我看到的唯一转换为 pfx 的命令需要单独文件中的 cer 和私钥:

Convert CER and Private Key to PFX:    
openssl pkcs12 -export -in certificatename.cer -inkey privateKey.key -out certificatename.pfx -certfile  cacert.cer

虽然我同意这不是真正的编程并且可以说是离题的,但社区显然接受了许多关于用于(加密)密钥和证书的命令行工具(openssl、keytool、certutil 等)的类似问题(投票)——但是none我看到直接解决了这一点。

openssl pkcs12 -export 上的不同选项允许您在不同的文件中提供片段,但这不是必需的。如果你在一个 PEM 文件中确实有私钥 证书链,默认情况下由 pkcs12 [not -export] 输出,你可以从那个文件中读取所有内容文件:

 openssl pkcs12 -export -in file -out p12
 # or ONLY IF the privatekey is first in the file
 openssl pkcs12 -export <file -out p12

你甚至可以组合 'on the fly' 只要你把私钥放在第一位:

 cat privkey.pem mycert.pem chain.pem | openssl pkcs12 -export -out p12

您可以使用以下命令将 PEM(.pem、.crt、.cer)转换为 PFX:

openssl pkcs12 -export -out **<your_new_file_name>**.pfx -inkey **<private_key_of_your_existing_certificate>**.key -in **<your_existing_certificate_file>**.crt

这对于上述所有文件都非常通用。