certs

package
v1.26.0-alpha1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 22, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

The certs package provides functions for handling TLS certificates and keys.

The certs package provides functions for handling TLS certificates and keys.

The certs package provides functions for handling TLS certificates and keys.

Index

Constants

View Source
const (
	PEMExtension      = ".pem"
	KEYExtension      = ".key"
	KeystoreExtension = ".db"
)
View Source
const DefaultKeyType = ECDH

DefaultKeyType is the default key type

Variables

This section is empty.

Functions

func AddCertChainToKeyStore

func AddCertChainToKeyStore(h host.Host, path string, password *config.Plaintext, alias string, key *memguard.Enclave, certChain ...*x509.Certificate) error

AddCertChainToKeyStore adds a private key and certificate chain to the keystore at the specified path on the given host. If the keystore does not exist, it is created. If password is nil, "changeit" is used.

The alias parameter specifies the alias under which to store the key and certificate chain.

Any existing entry with the same alias is deleted before adding the new key and certificate chain.

The certChain is not validated; the caller is responsible for ensuring that it is correct.

func AddRootsToTrustStore

func AddRootsToTrustStore(h host.Host, path string, password *config.Plaintext, roots ...*x509.Certificate) error

AddRootsToTrustStore adds the given root certificates to the truststore at the specified path on the given host. If the truststore does not exist, it is created. If password is nil, "changeit" is used.

Any existing entries with the same alias as a root certificate are deleted before adding the new root certificates. Aliases are derived from the Subject Common Name of each certificate.

Any certificates that are not root CAs are ignored.

func CertificateComments

func CertificateComments(cert *x509.Certificate, titles ...string) []byte

CertificateComments returns a byte slice containing comments about the given x509 certificate. If titles are provided they are included at the top of the comments, if not a default title of "Certificate" is used.

func CheckKeyMatch

func CheckKeyMatch(key *memguard.Enclave, cert *x509.Certificate) bool

CheckKeyMatch returns true if the DER encoded private key matches the public key in the provided x509 certificate.

func CreateCertificate

func CreateCertificate(template, parent *x509.Certificate, signingKey *memguard.Enclave) (cert *x509.Certificate, key *memguard.Enclave, err error)

CreateCertificate creates a new certificate and private key given the signing cert and key. Returns a certificate and private key. Keys are usually PKCS#8 encoded and so need parsing after unsealing.

func DecodePEM

func DecodePEM(data ...[]byte) (leaf *x509.Certificate, intermediates, roots []*x509.Certificate, keys []*memguard.Enclave, err error)

DecodePEM decodes PEM formatted data and returns the first leaf certificate and slices of certificates (intermediates, roots) and private keys found. Encrypted private keys and other types of blocks are not supported and will be skipped. If there are no certificates or private keys found then empty clients are returned without error.

func GenerateKey

func GenerateKey(keyType KeyType) (privateKey *memguard.Enclave, publicKey any, err error)

GenerateKey returns a PKCS#8 DER encoded private key as an enclave using the keyType specified.

func IndexPrivateKey

func IndexPrivateKey(keys []*memguard.Enclave, cert *x509.Certificate) int

IndexPrivateKey tests the slice DER encoded private keys against the x509 cert and returns the index of the first match, or -1 if none of the keys match.

func IsValidLeafCert

func IsValidLeafCert(cert *x509.Certificate) bool

IsValidLeafCert returns true if the provided certificate is a valid leaf certificate. A valid leaf certificate is not a CA, has the DigitalSignature key usage, has at least one extended key usage, and is between its NotBefore and NotAfter dates.

func IsValidRootCA

func IsValidRootCA(cert *x509.Certificate) bool

IsValidRootCA returns true if the provided certificate is a valid root CA certificate. A valid root CA is self-signed and has appropriate basic constraints as well as either an empty AuthorityKeyId or one that matches the SubjectKeyId. It must also be between its NotBefore and NotAfter dates.

func IsValidSigningCA

func IsValidSigningCA(cert *x509.Certificate) bool

IsValidSigningCA returns true if the provided certificate is a valid signing CA certificate. A valid signing CA is a CA certificate with appropriate basic constraints for signing (MaxPathLenZero) and is between its NotBefore and NotAfter dates.

func ParseCertChain

func ParseCertChain(cert ...*x509.Certificate) (leaf *x509.Certificate, intermediates []*x509.Certificate, root *x509.Certificate, err error)

ParseCertChain tries to verify the provided certificate chain. It returns the leaf certificate, any intermediates and any root certificate found in the chain. It returns an error if verification fails. The first certificate in the certs provided is assumed to be the leaf certificate. The order of the remaining certificates does not matter.

func ParsePrivateKey

func ParsePrivateKey(key *memguard.Enclave) (privatekey any, err error)

ParsePrivateKey parses the DER encoded private key enclave, first as PKCS#8 and then as a PKCS#1 and finally as SEC1 (EC) if that fails. It returns the private key or an error.

func PrivateKeyComments

func PrivateKeyComments(key *memguard.Enclave, titles ...string) []byte

PrivateKeyComments returns a byte slice containing comments about the given private key. If titles are provided they are included at the top of the comments, if not a default title of "Private Key" is used.

func PublicKey

func PublicKey(key *memguard.Enclave) (publicKey crypto.PublicKey, err error)

PublicKey parses the DER encoded private key enclave and returns the public key if successful. It will first try as PKCS#8 and then PKCS#1 if that fails and finally as SEC1 (EC). Returns an error if parsing fails.

func ReadCACertPool

func ReadCACertPool(h host.Host, path string) (pool *x509.CertPool, ok bool)

ReadCACertPool reads a local PEM file containing CA certificates and returns a *x509.CertPool and the number of valid root CAs found. Any certificates that are not valid root CAs are skipped.

func ReadCertPool

func ReadCertPool(h host.Host, path string) (pool *x509.CertPool)

ReadCertPool returns a certificate pool loaded from the file on host h at path. If there is any error a nil pointer is returned.

func ReadCertificates

func ReadCertificates(h host.Host, path string) (certs []*x509.Certificate, err error)

ReadCertificates reads and parses all certificates from the PEM file on host h at path. If the files cannot be read an error is returned. If no certificates are found in the file then no error is returned. The returned certificates are not validated beyond the parsing functionality of the underlying Go crypto/x509 package.

func ReadPrivateKey

func ReadPrivateKey(h host.Host, file string) (key *memguard.Enclave, err error)

ReadPrivateKey reads file on host h as an unencrypted, PEM-encoded private key and saves the der format key in a memguard.Enclave

func Template

func Template(cn string, options ...TemplateOption) (template *x509.Certificate)

Template creates a basic x509 certificate template with the given parameters. The caller can modify the template as needed before using it to create a certificate. If duration is zero, a default of 365 days is used.

func UpdateCACertsFileFromTrustStore

func UpdateCACertsFileFromTrustStore(h host.Host, truststorePath string, truststorePassword *config.Plaintext, caBundlePath string) (updated bool, err error)

UpdateCACertsFileFromTrustStore updates the CA bundle file at caBundlePath with any root CA certificates found in the truststore at truststorePath. If password is nil, "changeit" is used. It returns updated true if the CA bundle file was updated.

func UpdateCACertsFiles

func UpdateCACertsFiles(h host.Host, basePath string, roots ...*x509.Certificate) (updated bool, err error)

UpdateCACertsFiles appends the given root certificates to the root certificate file at the specified path on the given host. It ensures that all the given certificates are present in the file, appending any that are missing. If the file does not exist or is empty, it will be created with the provided certificates. Returns true if the file was updated (certificates added or file created), false if no changes were made.

Returns an error if writing the file fails.

Any non-root CA or expired certificates in the provided certs slice are ignored. Additionally, any non-root CA or expired certificates already present in the existing root certificate file are removed.

The caller is responsible for locking access to the root cert file if concurrent access is possible.

func Verify

func Verify(certs ...*x509.Certificate) (ok bool)

Verify verifies the provided certificates as a chain. It returns true if verification is successful. Only one leaf, zero or more intermediates and zero or one root certificate should be provided. If there is no leaf certificate then the first intermediate is used as the leaf. If there is only one or more root certificates then the function returns true.

func WriteCertificates

func WriteCertificates(h host.Host, certPath string, certs ...*x509.Certificate) (err error)

WriteCertificates concatenate certs in PEM format and writes to path on host h. Certificates that are expired are skipped, only errors from writing the resulting file are returned. Certificates are written in the order provided. Directories in the path are created with 0755 permissions if they do not already exist. The certificate file is created with 0644 permissions (before umask).

func WriteCertificatesAndKeyTo

func WriteCertificatesAndKeyTo(w io.Writer, key *memguard.Enclave, certChain ...*x509.Certificate) (n int, err error)

WriteCertificatesAndKeyTo writes the given certificate and optional private key in PEM format to the provided io.Writer. The total number of bytes written and any error encountered are returned.

func WriteCertificatesTo

func WriteCertificatesTo(w io.Writer, certs ...*x509.Certificate) (n int, err error)

WriteCertificatesTo writes the given certificates in PEM format to the provided io.Writer. Certificates that are expired are skipped. The total number of bytes written and any error encountered are returned.

func WriteNewRootCert

func WriteNewRootCert(basefilepath string, cn string, keytype KeyType) (root *x509.Certificate, err error)

WriteNewRootCert creates a new root certificate and private key and writes it locally with dir and file basefilepath with .pem and .key extensions. If overwrite is true then any existing certificate and key is overwritten.

func WriteNewSigningCert

func WriteNewSigningCert(basefilepath string, rootCert *x509.Certificate, rootKey *memguard.Enclave, cn string) (signing *x509.Certificate, err error)

WriteNewSigningCert creates a new signing certificate and private key with the path and file base name basefilepath. You must provide a valid root certificate and key in rootbasefilepath. If overwrite is true than any existing cert and key are overwritten.

The certificate is returned on success, but the private key is not.

func WriteNewSigningCertTo

func WriteNewSigningCertTo(w io.Writer, rootCert *x509.Certificate, rootKey *memguard.Enclave, cn string) (n int, err error)

WriteNewSigningCertTo creates a new signing certificate and private key signed by the given root certificate and key, writing the resulting private key and certificate in PEM format to the provided io.Writer. The total number of bytes written and any error encountered are returned.

func WritePrivateKey

func WritePrivateKey(h host.Host, keypath string, key *memguard.Enclave) (err error)

WritePrivateKey writes a DER encoded private key as a PKCS#8 encoded PEM file to path on host h. sets file permissions to 0600 (before umask). Directories in the path are created with 0755 permissions if they do not already exist.

func WritePrivateKeyTo

func WritePrivateKeyTo(w io.Writer, key *memguard.Enclave) (n int, err error)

WritePrivateKeyTo writes the given private key in PEM format to the provided io.Writer. The total number of bytes written and any error encountered are returned.

func WriteTrustStore

func WriteTrustStore(h host.Host, path string, password *config.Plaintext, roots ...*x509.Certificate) error

WriteTrustStore writes the given root certificates to a keystore at the specified path on the given host. If password is nil, "changeit" is used. Any certificates that are not valid root CAs are ignored. Any existing file is overwritten.

Types

type CertificateBundle

type CertificateBundle struct {
	Leaf      *x509.Certificate
	FullChain []*x509.Certificate
	Root      *x509.Certificate
	Key       *memguard.Enclave
	Valid     bool
}

CertificateBundle holds a leaf certificate and a certificate chain along with an optional private key (of the first cert in the chain, which is normally a leaf) and a root certificate. If there is no leaf certificate then Leaf is nil and FullChain[0] is the first intermediate, if any.

Valid should be set to true if the bundle has been verified as consistent from FullChain[0] to root and the private key applies FullChain[0] (but without revocation checks).

func P12ToCertBundle

func P12ToCertBundle(pfxPath string, password *config.Plaintext) (certBundle *CertificateBundle, err error)

func ParsePEM

func ParsePEM(data ...[]byte) (bundle *CertificateBundle, err error)

ParsePEM parses PEM formatted data blocks and returns a CertificateBundle. If it contains a verifiable chain and a private key that matches the leaf certificate it then it sets Valid to true. Only if Valid is true can the order of the certificates be relied upon.

Encrypted private keys are not supported and will be skipped.

type KeyStore

type KeyStore struct {
	keystore.KeyStore
}

func ReadKeystore

func ReadKeystore(h host.Host, path string, password *config.Plaintext) (k *KeyStore, err error)

ReadKeystore returns a keystore.

If password is nil, "changeit" is used.

The file is first attempted to be read as a modern keystore, if that fails it is tried as a JCEKS formatted keystore.

func (*KeyStore) AddKeystoreKey

func (k *KeyStore) AddKeystoreKey(alias string, key *memguard.Enclave, password *config.Plaintext, certs ...*x509.Certificate) (err error)

AddKeystoreKey adds a private key and certificates to the keystore.

If password is nil it uses "changeit" as the keystore password.

func (*KeyStore) AddTrustedCertificate

func (k *KeyStore) AddTrustedCertificate(alias string, cert *x509.Certificate) (err error)

AddTrustedCertificate adds a trusted certificate to the keystore.

func (*KeyStore) WriteKeystore

func (k *KeyStore) WriteKeystore(h host.Host, path string, password *config.Plaintext) (err error)

WriteKeystore writes the keystore to the given path. If password is nil, "changeit" is used.

type KeyType

type KeyType string
const (
	RSA     KeyType = "rsa"
	ECDSA   KeyType = "ecdsa"
	ED25519 KeyType = "ed25519"
	ECDH    KeyType = "ecdh"
)

func PrivateKeyType

func PrivateKeyType(der *memguard.Enclave) (keyType KeyType)

PrivateKeyType returns the type of the DER encoded private key, suitable for use to NewPrivateKey

func (*KeyType) Set

func (k *KeyType) Set(s string) error

func (KeyType) String

func (k KeyType) String() string

func (*KeyType) Type

func (k *KeyType) Type() string

type TemplateOption

type TemplateOption func(*templateOptions)

func BasicConstraintsValid

func BasicConstraintsValid() TemplateOption

func DNSNames

func DNSNames(names ...string) TemplateOption

func Days

func Days(days int) TemplateOption

func EmailAddresses

func EmailAddresses(emails ...string) TemplateOption

func ExtKeyUsage

func ExtKeyUsage(eku ...x509.ExtKeyUsage) TemplateOption

func IPAddresses

func IPAddresses(ips ...string) TemplateOption

func IsCA

func IsCA() TemplateOption

func KeyUsage

func KeyUsage(ku x509.KeyUsage) TemplateOption

func MaxPathLen

func MaxPathLen(len int) TemplateOption

func SANsFromCert

func SANsFromCert(cert *x509.Certificate) TemplateOption

SANsFromCert sets the Subject Alternative Names from an existing certificate

func URIs

func URIs(uris ...string) TemplateOption

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL