package main // getcert // ver. 1.0 // coded by Kenar // Ref: // https://stackoverflow.com/questions/54930751/\ // how-to-get-x509-certificate-from-http-client-in-go import( "os" . "fmt" "net/http" "encoding/pem" ) var usage = "usage: getcert url" func Error(s interface{}){ Fprintln(os.Stderr,s) os.Exit(1) } func main(){ var pb pem.Block args := os.Args[1:] if len(args) != 1 { Error(usage) } url := args[0] client := http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } req, err := http.NewRequest("HEAD", url, nil) if err != nil { Error(err) } resp, err := client.Do(req) if err != nil { Error(err) } if resp.TLS == nil { Error("Not TLS") } certificates := resp.TLS.PeerCertificates if len(certificates) == 0 { Error("No certificate") } ncert := len(certificates) for k:=0; k < ncert; { cert := certificates[k] Println("Subject",(*cert).Subject) Println("Issuer",(*cert).Issuer) pb.Type = "CERTIFICATE" pb.Bytes = cert.Raw if err := pem.Encode(os.Stdout, &pb); err != nil { Error(err) } k++ if k != ncert { Println() } } }