Last active
April 28, 2022 13:45
-
-
Save devtdeng/4f6adcb5a306f2ae035a2e7d9f724d17 to your computer and use it in GitHub Desktop.
Verify a certificate with chain with golang crypto library
This file contains hidden or 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/x509" | |
"encoding/pem" | |
"io/ioutil" | |
"log" | |
"os" | |
) | |
func main() { | |
log.Printf("Usage: verify_certificate SERVER_NAME CERT.pem CHAIN.pem") | |
serverName := os.Args[1] | |
certPEM, err := ioutil.ReadFile(os.Args[2]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
rootPEM, err := ioutil.ReadFile(os.Args[3]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
roots := x509.NewCertPool() | |
ok := roots.AppendCertsFromPEM([]byte(rootPEM)) | |
if !ok { | |
panic("failed to parse root certificate") | |
} | |
block, _ := pem.Decode([]byte(certPEM)) | |
if block == nil { | |
panic("failed to parse certificate PEM") | |
} | |
cert, err := x509.ParseCertificate(block.Bytes) | |
if err != nil { | |
panic("failed to parse certificate: " + err.Error()) | |
} | |
opts := x509.VerifyOptions{ | |
Roots: roots, | |
DNSName: serverName, | |
Intermediates: x509.NewCertPool(), | |
} | |
if _, err := cert.Verify(opts); err != nil { | |
panic("failed to verify certificate: " + err.Error()) | |
} | |
log.Printf("verification succeeds") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example from the docs is likely what people landing here are looking for: https://golang.org/pkg/crypto/x509/#example_Certificate_Verify