我知道有很多命令 (openssl) 可以将 pfx 导出到 pem,但我需要做一些不同的事情:我需要将公钥导出到一个 pem 文件,将私钥导出到另一个文件。大多数命令和站点(一些站点将 pfx 格式转换为我需要的任何格式)只会生成一个 *.pem 文件。
谢谢。
最佳答案
Meta:这不是编程或开发问题,很可能会作为题外话关闭。
如果您想要私钥和证书(包含公钥但不是公钥本身),这是其他堆栈中几个问题的骗局,其中它是主题性的,至少包括:
https://security.stackexchange.com/questions/3779/how-can-i-export-my-private-key-from-a-java-keytool-keystore/
https://serverfault.com/questions/715827/how-to-generate-key-and-crt-file-from-jks-file-for-httpd-apache-server
https://serverfault.com/questions/806141/is-the-alert-ssl3-read-bytessslv3-alert-bad-certificate-indicating-that-the-s (披露:我的回答)
或者,由于 PEM 文件是结构化文本,您可以通过任意数量的文本处理程序(例如 awk)解析单个 pkcs12
命令的输出:
openssl pkcs12 <p12 | awk '/-BEGIN ENC/,-END ENC/{print >"privkey"} \
/-BEGIN CERT/,/-END CERT/{if(!n)print >"cert"} /-END CERT/{n++}'
# for unencrypted privatekey add -nodes and select BEGIN/END PRIV
如果您真的想要公钥,您可以从私钥或证书以算法通用的 X.509 SubjectPublicKeyInfo 形式创建它:
# from the certificate
openssl x509 <certfile -noout -pubkey >pubkey
openssl pkcs12 <p12file -nokeys -clcerts | openssl x509 -noout -pubkey >pubkey
# from the privatekey
openssl pkey <privkey -pubout >pubkey
openssl pkcs12 <p12file -nocerts -nodes | openssl pkey -pubout >pubkey
这种格式被一些 OpenSSL 函数(称它为 PUBKEY 以区别于几个特定算法的公钥)和低级 Java(称它为 X509EncodedKeySpec
)使用,几乎没有别的。注意使用裸公钥的系统通常是不安全的;这正是大多数系统将公钥嵌入证书中的原因。
如果 key 是 RSA 并且您想要特定于算法的 (PKCS1 RSAPublicKey) 格式,请在 OpenSSL 1.1.0(并且可能是更高版本)中使用:
# from the SPKI publickey as above
openssl rsa <RSApub_spki [-inform DER] -pubin -RSAPublicKey_out [-outform DER] >RSApub_pkcs1
# from the privatekey
openssl rsa <RSAprivate [-inform DER] -RSAPublicKey_out [-outform DER] >RSApub_pkcs1
少数 OpenSSL 函数和 AFAIK 很少使用它;请参阅上面的警告。
关于ssl - 选择 pfx 至 pem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48568267/