GoLang问题:如何在GoLang中传递key.pem,cert.pem,chain.pem证书

时间:2016-04-13 11:34:32

标签: go https client-certificates

我尝试使用以下代码,传递cert.pem,key.pem和..chain.pem,但获取状态:500,因为服务无法读取这些https RESTful webservice的证书。我浏览了网络中的所有示例并尝试了但仍然得到相同的异常。

package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "strings"
    "io"        
)

func main() {

    UserName := "user"
    appName := "AP"
    PasswordKey := "key"
    ServerName := "server"
    Sid := "sid" 

    // Load client cert
    cert, err := tls.LoadX509KeyPair("/cert.pem", "/key.pem")
    if err != nil {
        log.Fatal(err)
    }

    // Load CA cert
    caCert, err := ioutil.ReadFile("/xyz.chain.pem")
    if err != nil {
        log.Fatal(err)
    }
    caCertPool := x509.NewCertPool()
    ok := caCertPool.AppendCertsFromPEM(caCert)
    if !ok {
        panic("failed to parse root certificate")
    }

    fmt.Println("CERT: ",cert)

    // Setup HTTPS client
    tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{cert},
        ServerName: "serverName",
        RootCAs:      caCertPool,
    }

    tlsConfig.BuildNameToCertificate()
    transport := &http.Transport{TLSClientConfig: tlsConfig}
    client := &http.Client{Transport: transport}
    fmt.Println("CLIENT: ",client)

 r := strings.NewReader("{\"userName\" : \"" +UserName+"\",\"appName\" : \""+appName+"\",\"passwordKey\" : \""+PasswordKey+"\",\"serverName\" : \""+ServerName+"\",\"sid\" : \""+Sid+"\"}")
        lr := io.Reader(r)


    resp, err := client.Post("https://xzytr/password/txt","application/json",lr)
    if err != nil {
        fmt.Println(err)
    }

    contents, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("%s\n", string(contents))
}

0 个答案:

没有答案