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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序