How to create a tls client with ca certificates in GO?
Asked Answered
T

1

6

I want to create a tls client using the net/http in GO how can I create it given the ca certificates?

Thordis answered 26/7, 2016 at 6:54 Comment(0)
B
12
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()

    // Load client cert
    cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
    if err != nil {
        log.Fatal(err)
    }

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

    // Setup HTTPS client
    tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{cert},
        RootCAs:      caCertPool,
    }
    tlsConfig.BuildNameToCertificate()
    transport := &http.Transport{TLSClientConfig: tlsConfig}
    client := &http.Client{Transport: transport}

    // Do GET something
    resp, err := client.Get("https://localdev.local:8443")
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    // Dump response
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(data))
}

Mostly borrowed from this gist. And here is a great article to work with TLS in Go: https://ericchiang.github.io/tls/go/https/2015/06/21/go-tls.html

Blanketyblank answered 26/7, 2016 at 7:50 Comment(2)
Thank you I accepted your answer but I can't upvote until i reach 15 reputationsThordis
No one provid private key. The client always use public key to connect.Verboten

© 2022 - 2024 — McMap. All rights reserved.