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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看