Created
August 21, 2019 03:23
-
-
Save coconut49/8c82eb40b6cc1d25917219a07be3b6b6 to your computer and use it in GitHub Desktop.
Golang SSL Pinning
This file contains 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 ( | |
"context" | |
"crypto/sha256" | |
"crypto/tls" | |
"crypto/x509" | |
"encoding/pem" | |
"errors" | |
"fmt" | |
"github.com/sirupsen/logrus" | |
"io/ioutil" | |
"net/http" | |
) | |
func main() { | |
CalcCertFingerprint("cert.crt") | |
} | |
func CalcCertFingerprint(certname string) string { | |
cert, err := ioutil.ReadFile(certname) | |
if err != nil { | |
panic(err) | |
} | |
p, _ := pem.Decode(cert) | |
sum256 := sha256.Sum256(p.Bytes) | |
logrus.Infof("%x", sum256) | |
return fmt.Sprintf("%x", sum256) | |
} | |
// Usage | |
// tr := &http.Transport{ | |
// TLSClientConfig: &tls.Config{ | |
// VerifyPeerCertificate: VerifyPeerCertificate, | |
// InsecureSkipVerify: true, | |
// }, | |
// } | |
func VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { | |
var fingerprints []string | |
for _, rawCert := range rawCerts { | |
cert, _ := x509.ParseCertificate(rawCert) | |
logrus.Infoln(cert.Subject) | |
fingerprints = append(fingerprints, fmt.Sprintf("%x", sha256.Sum256(rawCert))) | |
} | |
for _, fingerprint := range fingerprints { | |
logrus.Infoln(fingerprint) | |
if fingerprint == "76b5b519201931f938f0afef58493a3c961516a1225b948d8f138d2974c8bec7" { | |
return nil | |
} | |
} | |
return errors.New("certificate signature does not match") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment