go语言实现CA证书双向访问

package main

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

type MyMux struct {
    
    
}

func (p *MyMux) ServeHTTP(res http.ResponseWriter, req *http.Request) {
    
    
	fmt.Fprintf(res, "Hi, This is an example of https service in golang!\n")

	fmt.Fprintf(res,
		`[{"Name":"jason","Age":35,"Weight":60.3,"Speciality":"computer science","Hobby":["tennis","swimming","reading"],"Score":725.5,"Secret":"SRRMb3ZlFFlvdSE="}]`)
}

func main() {
    
    
	pool := x509.NewCertPool()
	caCertPath := "ca.crt"

	caCrt, err := ioutil.ReadFile(caCertPath)
	if err != nil {
    
    
		fmt.Println("ReadFile err:", err)
		return
	}
	pool.AppendCertsFromPEM(caCrt)

	s := &http.Server{
    
    
		Addr:    ":8081",
		Handler: &MyMux{
    
    },
		TLSConfig: &tls.Config{
    
    
			ClientCAs:  pool,
			ClientAuth: tls.RequireAndVerifyClientCert,
		},
	}

	err = s.ListenAndServeTLS("server.crt", "server.key")
	if err != nil {
    
    
		fmt.Println("ListenAndServeTLS err:", err)
	}
}
package main

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

func main() {
    
    
    pool := x509.NewCertPool()
    caCertPath := "ca.crt"

    caCrt, err := ioutil.ReadFile(caCertPath)
    if err != nil {
    
    
        fmt.Println("ReadFile err:", err)
        return
    }
    pool.AppendCertsFromPEM(caCrt)

    cliCrt, err := tls.LoadX509KeyPair("client.crt", "client.key")
    if err != nil {
    
    
        fmt.Println("Loadx509keypair err:", err)
        return
    }

    tr := &http.Transport{
    
    
        TLSClientConfig: &tls.Config{
    
    
            RootCAs:      pool,
            Certificates: []tls.Certificate{
    
    cliCrt},
        },
    }
    client := &http.Client{
    
    Transport: tr}
    resp, err := client.Get("https://zigoo.com:8081")
    if err != nil {
    
    
        fmt.Println("Get error:", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}


猜你喜欢

转载自blog.csdn.net/weixin_43443216/article/details/111354120