123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- package cryptutil
- import (
- "bytes"
- "crypto/md5"
- "crypto/sha1"
- "crypto/sha256"
- "crypto/x509"
- "encoding/pem"
- "errors"
- "fmt"
- "io/ioutil"
- "os"
- )
- func ReadX509CertsFromFile(filename string) ([]*x509.Certificate, error) {
- var err error
- var certs []*x509.Certificate
- file, err := os.OpenFile(filename, os.O_RDONLY, 0660)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- certsString, err := ioutil.ReadAll(file)
- if err == nil {
- certs, err = ReadX509Certs(certsString)
- }
- return certs, err
- }
- func ReadX509Certs(certs []byte) ([]*x509.Certificate, error) {
- var blocks []byte
- for {
- var block *pem.Block
- block, certs = pem.Decode(certs)
- if block == nil {
- return nil, errors.New("PEM not parsed")
- }
- blocks = append(blocks, block.Bytes...)
- if len(certs) == 0 {
- break
- }
- }
- c, err := x509.ParseCertificates(blocks)
- if err != nil {
- return nil, err
- }
- return c, nil
- }
- func Sha1CertFingerprint(cert *x509.Certificate) string {
- return formatFingerprint(fmt.Sprintf("%x", sha1.Sum(cert.Raw)))
- }
- func Sha256CertFingerprint(cert *x509.Certificate) string {
- return formatFingerprint(fmt.Sprintf("%x", sha256.Sum256(cert.Raw)))
- }
- func Md5CertFingerprint(cert *x509.Certificate) string {
- return formatFingerprint(fmt.Sprintf("%x", md5.Sum(cert.Raw)))
- }
- func formatFingerprint(raw string) string {
- var buf bytes.Buffer
- for i, c := range raw {
- buf.WriteByte(byte(c))
- if (i+1)%2 == 0 && i != len(raw)-1 {
- buf.WriteByte(byte(':'))
- }
- }
- return buf.String()
- }
|