Add subjhash tool. Minor cleanups.

This commit is contained in:
Kyle Isom
2017-10-20 12:18:41 -07:00
parent 4fa6e4ab0e
commit d42c1fa1c5
4 changed files with 331 additions and 0 deletions

View File

@@ -2,7 +2,11 @@
package lib
import (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
@@ -79,6 +83,7 @@ var (
yearDuration = (365 * dayDuration) + (6 * time.Hour)
)
// Duration returns a prettier string for time.Durations.
func Duration(d time.Duration) string {
var s string
if d >= yearDuration {
@@ -102,3 +107,78 @@ func Duration(d time.Duration) string {
s += fmt.Sprintf("%dh%s", hours, d)
return s
}
// ReadCertificate reads a DER or PEM-encoded certificate from the
// byte slice.
func ReadCertificate(in []byte) (cert *x509.Certificate, rest []byte, err error) {
if len(in) == 0 {
err = errors.New("lib: empty certificate")
return
}
if in[0] == '-' {
p, remaining := pem.Decode(in)
if p == nil {
err = errors.New("lib: invalid PEM file")
return
}
rest = remaining
if p.Type != "CERTIFICATE" {
err = fmt.Errorf("lib: expected a CERTIFICATE PEM file, but have %s", p.Type)
return
}
in = p.Bytes
}
cert, err = x509.ParseCertificate(in)
return
}
// ReadCertificates tries to read all the certificates in a
// PEM-encoded collection.
func ReadCertificates(in []byte) (certs []*x509.Certificate, err error) {
var cert *x509.Certificate
for {
cert, in, err = ReadCertificate(in)
if err != nil {
break
}
if cert == nil {
break
}
certs = append(certs, cert)
if len(in) == 0 {
break
}
}
return certs, err
}
// LoadCertificate tries to read a single certificate from disk. If
// the file contains multiple certificates (e.g. a chain), only the
// first certificate is returned.
func LoadCertificate(path string) (*x509.Certificate, error) {
in, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
cert, _, err := ReadCertificate(in)
return cert, err
}
// LoadCertificates tries to read all the certificates in a file,
// returning them in the order that it found them in the file.
func LoadCertificates(path string) ([]*x509.Certificate, error) {
in, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return ReadCertificates(in)
}