duancan65665
2019-07-29 18:43 阅读 118
已采纳

如何从pkcs12商店加载x509密钥对?

I have a script that creates a PKCS12 store on a server via OpenSSL. I am developing a TLS/SSL server in Go and need to load the key pair from the created PKCS12 store. How do I pull the keypair from the PCKS12 store and load them?

Here is my code snippet, which is giving me an error:

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
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douzi4766 douzi4766 2019-08-01 07:31

    You don't need to load the keypair with the tls package because pkcs12.Decode already does that. Simply initialize a value of type 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,
    }
    

    Quoting 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.

    The documentation contains an example that shows how to use ToPEM to initialize a tls.Certificate.

    点赞 评论 复制链接分享

相关推荐