将 pfx 转换为 pem



我知道有很多命令(openssl)可以将pfx导出到pem,但我需要一件事:我需要将公钥导出到pem文件,将私钥导出到另一个文件。大多数命令和站点(某些站点将 pfx 格式转换为我需要的任何人)只会生成一个 *.pem 文件。

谢谢。

元维基:这不是一个编程或开发问题,很可能会因为题外话而被关闭。

如果你想要私钥和证书(包含公钥,但不是公钥本身),这是其他堆栈中几个问题的欺骗,至少包括:

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)使用,几乎没有其他内容。使用裸公钥的笔记系统通常是不安全的;这正是大多数系统在证书中嵌入公钥的原因。

如果密钥是 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没有其他任何东西;请参阅上面的警告。