feat: Cert helpers.

This commit is contained in:
jmug committed 2026-10-23 00:11:00 -07:00
1 parent 5ba8ca9417
commit b4b628210f
1 file changed
+40
+40
View File
@@ -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
}