diff --git a/pkg/pki/cert.go b/pkg/pki/cert.go new file mode 100644 index 0000000..783ed00 --- /dev/null +++ b/pkg/pki/cert.go @@ -0,0 +1,40 @@ +package pki + +import ( + "crypto/rand" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "math" + "math/big" + "os" +) + +// Generates a cyrptographically randon number to be used as a cert serial number. +func NewCertSerialNumber() *big.Int { + sn, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64)) + if err != nil { + panic(errors.New("Could not generate a serial number")) + } + return sn +} + +// ParseCertFromFile retrieves a certificate stored in PEM format from a file. +func ParseCertFromFile(fn string) (*x509.Certificate, error) { + pemBytes, err := os.ReadFile(fn) + if err != nil { + return nil, err + } + certBlock, _ := pem.Decode(pemBytes) + if certBlock == nil || certBlock.Type != PEMTypeCertificate { + return nil, fmt.Errorf("file was not PEM or first block wasn't %s", PEMTypeCertificate) + } + + cert, err := x509.ParseCertificate(certBlock.Bytes) + if err != nil { + return nil, err + } + + return cert, nil +}