发布于 1年前

Go语言客户端SSL认证代码示例

client_ssl_authenticate.go

package main

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

var (
    certFile = flag.String("cert", "someCertFile", "A PEM eoncoded certificate file.")
    keyFile  = flag.String("key", "someKeyFile", "A PEM encoded private key file.")
    caFile   = flag.String("CA", "someCertCAFile", "A PEM eoncoded CA's certificate file.")
)

func main() {
    flag.Parse()

    // 加载客户端的cert文件
    cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
    if err != nil {
        log.Fatal(err)
    }

    // 加载CA cert
    caCert, err := ioutil.ReadFile(*caFile)
    if err != nil {
        log.Fatal(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    // 设置客户端的https
    tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{cert},
        RootCAs:      caCertPool,
    }
    tlsConfig.BuildNameToCertificate()
    transport := &http.Transport{TLSClientConfig: tlsConfig}
    client := &http.Client{Transport: transport}

    // get请求测试
    resp, err := client.Get("https://localhost:8443")
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    // 
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(data))
}
©2020 edoou.com   京ICP备16001874号-3