我有Windows 7上的OpenSSL x64,我从谷歌代码上的OpenSSL -for- Windows下载的。我试着跑:

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" 

但是我得到了一个错误。

unable to load private key

如何使用OpenSSL从pkcs# 12存储中提取PEM格式的证书?


Try:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes

在那之后,你有:

newfile.crt.pem中的证书 newfile.key.pem中的私钥

如果要将证书和密钥放在同一个文件中,且没有密码,请使用以下方法,因为空密码将导致密钥无法导出:

openssl pkcs12 -in path.p12 -out newfile.pem -nodes

或者,如果你想为私钥提供一个密码,忽略-nodes并输入一个密码:

openssl pkcs12 -in path.p12 -out newfile.pem

如果您需要直接从命令行(例如脚本)输入PKCS#12密码,只需添加-passin pass:${password}:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'

你只需要提供一个密码。你可以在相同的命令行中使用以下语法完成:

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]

然后系统会提示您输入密码,以加密输出文件中的私钥。如果你想导出未加密的私钥(明文),在上面的行中包含“nodes”选项:

openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes

更多信息:http://www.openssl.org/docs/apps/pkcs12.html

如果可以使用Python,那么使用pyopenssl模块就更容易了。下面就是:

from OpenSSL import crypto

# May require "" for empty password depending on version

with open("push.p12", "rb") as file:
    p12 = crypto.load_pkcs12(file.read(), "my_passphrase")

# PEM formatted private key
print crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())

# PEM formatted certificate
print crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())

我有一个PFX文件,需要为NGINX创建KEY文件,所以我这样做:

openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes

然后我必须编辑密钥文件,并删除-----开始私钥-----的所有内容。之后NGINX接受KEY文件。

有一个免费的开源GUI工具KeyStore Explorer可以使用加密密钥容器。使用它,您可以将证书或私钥导出到单独的文件中,或将容器转换为其他格式(jks, pem, p12, pkcs12等)

#!/usr/bin/env python3
from optparse import Option
from OpenSSL import crypto
import os
import warnings
from getpass import getpass
warnings.filterwarnings("ignore", category=DeprecationWarning) 

def sanitize_path(path):
    return os.path.expandvars(os.path.expanduser(path))

def main(in_file, out_file, passphrase=None):
    if not passphrase:
        passphrase = getpass(prompt=("SSL Private Key Passphrase: "))
   
    in_file = sanitize_path(in_file)
    out_file = sanitize_path(out_file)
    
    with open(in_file, "rb") as input_file:
        p12 = crypto.load_pkcs12(input_file.read(), passphrase)
        pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())
    with open(out_file, "w") as output_file:
        output_file.write(pem.decode('utf-8'))

if __name__ == '__main__':
    from optparse import OptionParser
    usage = "usage: %prog  input_file output_file [passphrase]"
    p = OptionParser(usage=usage)
    opt, args = p.parse_args()
    main(*args)