Problem
You want to get your website SSL (pem format) certificate's fingerprint with Golang
Solution
If you want to generate the sha1
fingerprint for your pem file (for example, fullchain.cer
), with command line, you can do something like this:
$ openssl x509 -noout -fingerprint -sha1 -inform pem -in fullchain.cer
If you want to do the same in Golang, Go already has these built-in libraries you can use:
package main
import (
"bytes"
"crypto/sha1"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
)
func main() {
// read file content
pemContent, err := ioutil.ReadFile("./fullchain.cer")
if err != nil {
panic(err)
}
block, _ := pem.Decode(pemContent)
if block == nil {
panic("Failed to parse pem file")
}
// pass cert bytes
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic(err)
}
// generate fingerprint with sha1
// you can also use md5, sha256, etc.
fingerprint := sha1.Sum(cert.Raw)
var buf bytes.Buffer
for i, f := range fingerprint {
if i > 0 {
fmt.Fprintf(&buf, ":")
}
fmt.Fprintf(&buf, "%02X", f)
}
fmt.Printf("Fingerprint: %s\n", buf.String())
}
Top comments (0)