duancan65665 2019-07-29 18:43
浏览 132
已采纳

如何从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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog