Last active
April 10, 2024 01:57
-
-
Save michaljemala/d6f4e01c4834bf47a9c4 to your computer and use it in GitHub Desktop.
SSL Client Authentication Golang sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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://goldportugal.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)) | |
} |
BTW: it seems that BuildNameToCertificate()
is deprecated now (go 1.19.3). See: https://pkg.go.dev/crypto/tls#Config.BuildNameToCertificate
It looks like that you can just skip this call to let the library select the first compatible chain from tlsConfig.Certificates
.
You should be able to use https://pkg.go.dev/golang.org/x/crypto/pkcs12, e.g. like this:
pfxData, err := ioutil.ReadFile(*pfxFile) if err != nil { log.Fatal(err) } blocks, err := pkcs12.ToPEM(pfxData, "SOME_PASSWORD") // Change according to your setup if err != nil { log.Fatal(err) } var pemData []byte for _, b := range blocks { pemData = append(pemData, pem.EncodeToMemory(b)...) } cert, err := tls.X509KeyPair(pemData, pemData) // then just use the `cert` as per the snippetAlternatively, convert pfx to pem using
openssl pkcs12
.
Also worth noting that for .pfx
and the password way you would need the below. Just wanted to add more.
encoding/pem
golang.org/x/crypto/pkcs12
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not necessary in most cases. Some clients uses cert/key pair for authenication. When you don't or cannot use this feature of TLS, then you can create
tlsConfig
withoutcert