如何从 pkcs12 存储加载 x509 密钥对?

How do I load a x509 keypair from a pkcs12 store?

我有一个脚本可以通过 OpenSSL 在服务器上创建 PKCS12 存储。我正在用 Go 开发一个 TLS/SSL 服务器,需要从创建的 PKCS12 存储中加载密钥对。如何从 PCKS12 存储中提取密钥对并加载它们?

这是我的代码片段,它给我一个错误:

src/server.go:59:19: cannot use cert (type interface {}) as type []byte in argument to ioutil.WriteFile: need type assertion
src/server.go:60:19: cannot use key (type *x509.Certificate) as type []byte in argument to ioutil.WriteFile
 import "golang.org/x/crypto/pkcs12"


 // Read byte data from pkcs12 keystore
 p12_data, err := ioutil.ReadFile("../identify.p12")
 if err != nil {
     log.Fatal(err)
 }

 // Extract cert and key from pkcs keystore
 cert, key, err := pkcs12.Decode(p12_data, "123456")
    if err != nil {
        log.Println(err)
        return
    }

//Write cert and key out to filepath
ioutil.WriteFile("cert.pem", cert, 777)
ioutil.WriteFile("key.pem", key, 777)

log.SetFlags(log.Lshortfile)
cer, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
    log.Println(err)
    return
}

您不需要使用 tls 包加载密钥对,因为 pkcs12.Decode 已经这样做了。只需初始化一个 tls.Certificate:

类型的值
p12_data, err := ioutil.ReadFile("../identify.p12")
if err != nil {
    log.Fatal(err)
}

key, cert, err := pkcs12.Decode(p12_data, "123456") // Note the order of the return values.
if err != nil {
    log.Fatal(err)
}

tlsCert := tls.Certificate{
    Certificate: [][]byte{cert.Raw},
    PrivateKey:  key.(crypto.PrivateKey),
    Leaf:        cert,
}

引用 the documentation:

This function assumes that there is only one certificate and only one private key in the pfxData; if there are more use ToPEM instead.

该文档包含一个示例,说明如何使用 ToPEM 初始化 tls.Certificate。