I'm trying to find a function similar to Python's ssl.get_server_certificate()
, which takes a hostname-port pair and returns a PEM-encoded certificate, but I haven't had any luck.
I've done a fair bit of digging around, but the closest question I've found (Get remote ssl certificate in golang) did not help, nor did reading through the documentation for the package crypto/tls
. I'm new to Go, so I may have not understood something in the documentation
import (
"bytes"
"crypto/tls"
"encoding/pem"
)
func GetCertificatesPEM(address string) (string, error) {
conn, err := tls.Dial("tcp", address, &tls.Config{
InsecureSkipVerify: true,
})
if err != nil {
return "", err
}
defer conn.Close()
var b bytes.Buffer
for _, cert := range conn.ConnectionState().PeerCertificates {
err := pem.Encode(&b, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Raw,
})
if err != nil {
return "", err
}
}
return b.String(), nil
}
Usage:
certs, err := GetCertificatesPEM("example.com:443")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With