duanhan3067 2014-02-04 20:05
浏览 350
已采纳

Golang:如何在HTTP客户端的TLS配置中指定证书

I have a cert file, that location is: /usr/abc/my.crt and I want to use that cert for my tls config, so that my http client uses that certificate when communicate with other servers. My current code is as follows:

mTLSConfig := &tls.Config {
    CipherSuites: []uint16 {
        tls.TLS_RSA_WITH_RC4_128_SHA,
        tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
        tls.TLS_RSA_WITH_AES_128_CBC_SHA,
        tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
        tls.TLS_RSA_WITH_AES_128_CBC_SHA,
        tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
    }
}

mTLSConfig.PreferServerCipherSuites = true
mTLSConfig.MinVersion = tls.VersionTLS10
mTLSConfig.MaxVersion = tls.VersionTLS10

tr := &http.Transport{
    TLSClientConfig: mTLSConfig,
}

c := &http.Client{Transport: tr}

So how to assign a certificate in my TLS config? I see the certificate settings at http://golang.org/pkg/crypto/tls/#Config can someone suggest how to config my cert location there?

mTLSConfig.Config{Certificates: []tls.Certificate{'/usr/abc/my.crt'}} <-- is wrong because I am passing string.right? I DON'T have ANY other files such as .pem or .key etc, just only this my.cert. I am blank how to do it?

Earlier, I had edited the go source code http://golang.org/src/pkg/crypto/x509/root_unix.go and added /usr/abc/my.crt after line no. 12 and it worked. But the problem is my certificate file location can change, so I have removed the hardcoded line from root_unix.go and trying to pass it dynamically, when building TLSConfig.

  • 写回答

1条回答 默认 最新

  • douxie9347 2014-02-04 21:58
    关注

    You can replace the system CA set by providing a root CA pool in tls.Config.

    certs := x509.NewCertPool()
    
    pemData, err := ioutil.ReadFile(pemPath)
    if err != nil {
        // do error
    }
    certs.AppendCertsFromPEM(pemData)
    mTLSConfig.RootCAs = certs
    

    If you still want the system's roots however, I think you'll need to recreate the functionality in initSystemRoots(). I don't see any exposed method for merging a cert into the default system roots.

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

报告相同问题?

悬赏问题

  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译