Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch a certificate from a URL?

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

like image 764
Aor Avatar asked Oct 13 '17 17:10

Aor


1 Answers

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")
like image 187
Tim Cooper Avatar answered Sep 28 '22 00:09

Tim Cooper