TLS相互认证返回错误,因为主机和端口的组合需要TLS

时间:2018-12-03 14:02:14

标签: go

我正在尝试进行TLS相互身份验证设置,但是从服务器获取错误信息为This combination of host and port requires TLS.

下面是我要使用的代码。

package main

import (
    "crypto/tls"
    "crypto/x509"
    "io/ioutil"
    "log"
    "net"
    "net/http"
    "net/http/httputil" //"os"
    "time"
)

//HTTPClient will retrun an HTTP client back to user
type HTTPClient struct {
    *http.Client
}

//NewClient will return an HTTP client with TLS mutual Auth set
//Input: isSecure
//Return: HTTPClient
func NewClient() *HTTPClient {
    log.Println("Setting up TLS configuration")
    cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
    if err != nil {
        log.Fatal("Unable to read certificates ", err)
    }
    //load CA certificate
    caCert, err := ioutil.ReadFile("ca.pem")
    if err != nil {
        log.Fatal("Unable to read CA certificate ", err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    tlsConfig := &tls.Config{
        RootCAs:            caCertPool,              //RootCAs
        MinVersion:         tls.VersionTLS12,        //Support only TLS 1.2 or higher
        Certificates:       []tls.Certificate{cert}, //Reject any TLS certificate that cannot be validated
        InsecureSkipVerify: false,                   //Make sure we alway verify certificate
    }
    tlsConfig.BuildNameToCertificate()
    transport := &http.Transport{
        TLSClientConfig: tlsConfig,
        DialTLS: (&net.Dialer{
            Timeout: 30 * time.Second,
        }).Dial,
        TLSHandshakeTimeout: 30 * time.Second,
        MaxIdleConns:        10,
    }
    return &HTTPClient{
        Client: &http.Client{
            Transport: transport,
            Timeout:   time.Second * 10,
        },
    }
}

func main() {
    url := "https://35.184.226.101:443/test"
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Println("Error while creating request for ", url)
        return
    }
    resp, err := NewClient().Do(req)
    response, err := httputil.DumpResponse(resp, true)
    if err != nil {
        log.Println("Error while dumping Request ", err)
    }
    log.Println(string(response))
    /* Output
        018/12/03 19:19:38 Setting up TLS configuration
    2018/12/03 19:19:38 HTTP/1.1 400
    Connection: close
    Content-Type: text/plain;charset=ISO-8859-1

    Bad Request
    This combination of host and port requires TLS.
    */

}

任何人都认为问题出在哪里。还有如何启用额外的跟踪,以便我们可以获得更多信息。

0 个答案:

没有答案