Files
2026-10-23 00:11:00 -07:00

41 lines
909 B
Go

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
}