pcert

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

README

pcert

PkgGoDev

pcert aims to ease the creation of x509 certificates and keys.

The simple case is as easy as this:

pcert create

This would write the certificate and key to standard output.

You can write the certificate and key to a file by specifying either only the certificate path or both pathes:

pcert create tls.crt
pcert create tls.crt tls.key

The two invocations above are equivalent. When omitting the path for the key file the key file is written into the same directory as the certificate to a file with the same name but ending in .key.

Quick start

Self-signed server certificate

pcert create tls.crt --server --dns myserver.example.com

Signed certificates (CA)

To create your own CA and sign certificates with it you first create a CA (self-signed) certificate:

pcert create ca.crt --ca --name "My CA"

Then you can create and sign certificates with it:

# server
pcert create server.crt --server --dns foo.example.com --dns bar.example.com

# client
pcert create client.crt --client --name "my client"

Auto completion

Shell completion can be enabled for bash, zsh, fish and ps (Power Shell). It supports not only completion for the commands, but also for certain flags (e.g. --key-usage, --ext-key-usage, --sign-alg) where the valid options are hard to remember.

source <( pcert completion bash )

Expiry

The validity period of certificates default to one year starting from the creation time. The period can be changed by using the options --not-before, --not-after and --expiry. The options --not-before and --not-after allow to set the NotBefore and NotAfter value to a certain date (RFC3339):

pcert create --not-before 2020-01-01T12:00:00+01:00 --not-after 2020-06-01T12:00:00+01:00

The option --expiry allows to specify a duration instead of explicit dates:

# certificate valid until 90days from now
pcert create --expiry 90d

# certificate valid until 3 years (3 * 365 days)
pcert create --expiry 3y

Environment variables

All command line flags can also be set using environment variables. For this you have to make the flag name upper-case, repalce - with _ and prefix it with PCERT_.

For example:

  • --sign-cert=ca.crt => PCERT_SIGN_CERT=ca.crt
  • --subject-country CH => PCERT_SUBJECT_COUNTRY=CH

Command line flags take precedence over environment variables. Be aware that for flags you can specify multiple times (e.g. --dns) the values from the environment and form the command line flags are combined.

Examples

Local CA

Here is an example of how you could use pcert to create a local CA:

Create CA certificate and key in ~/pki:

mkdir ~/pki
pcert create ~/pki/ca.crt --ca

If you like you can add the newly created certificate ~/pki/ca.crt to you system trust store.

Now we set PCERT_SIGN_CERT that all newly created certificates are signed with our CA in ~/pki. This environment variable could be added to .bashrc for example:

export PCERT_SIGN_CERT=~/pki/ca.crt
export PCERT_SIGN_KEY=~/pki/ca.key

From now on if we use pcert create it creates certificates which are signed by our local CA. If you still would create a self-signed certificate you would have to set --sign-cert="".

Intermediate CA

This example shows how to make an intermediate CA certificate:

Create root CA certificate and key:

pcert create root.crt --ca

Create intermediate CA certificate:

pcert create intermediate.crt --ca --sign-cert root.crt

Create server certificate from the intermediate CA:

pcert create server.crt --sign-cert indtermediate.crt --dns myserver.example.com

Documentation

Overview

Package pcert aims to ease the creation of x509 certificates and keys. This package provides the following main functions:

  • Create: creates a certificate and a key
  • Request: creates a CSR and a key
  • Sign: signs a certificate or a CSR with an existing certificate and key

The results of the functions which return certificates, CSRs and keys are all PEM encoded.

All functions without special suffix refer to a certificates. Functions for CSR and Key use an appropriate suffix. For example the function Load loads a certificate from a file, whereas LoadKey or LoadCSR are for keys resp. CSRs.

    import (
            "io/ioutil"

            "github.com/dvob/pcert"
    )

    func main() {
            cert := pcert.NewServerCertificate("www.example.local")

			// self-signed
            certPEM, keyPEM, _ := pcert.Create(cert, nil, nil)

            _ = ioutil.WriteFile("server.crt", certPEM, 0644)
            _ = ioutil.WriteFile("server.key", keyPEM, 0600)

    }

Index

Examples

Constants

View Source
const (
	// DefaultValidityPeriod is the validity period used for certificates which have not set NotAfter explicitly
	DefaultValidityPeriod = time.Hour * 24 * 365
)

Variables

View Source
var ExtKeyUsages = map[string]x509.ExtKeyUsage{
	"Any":                            x509.ExtKeyUsageAny,
	"ClientAuth":                     x509.ExtKeyUsageClientAuth,
	"CodeSigning":                    x509.ExtKeyUsageCodeSigning,
	"EmailProtection":                x509.ExtKeyUsageEmailProtection,
	"IPSECEndSystem":                 x509.ExtKeyUsageIPSECEndSystem,
	"IPSECTunnel":                    x509.ExtKeyUsageIPSECTunnel,
	"IPSECUser":                      x509.ExtKeyUsageIPSECUser,
	"MicrosoftCommercialCodeSigning": x509.ExtKeyUsageMicrosoftCommercialCodeSigning,
	"MicrosoftKernelCodeSigning":     x509.ExtKeyUsageMicrosoftKernelCodeSigning,
	"MicrosoftServerGatedCrypto":     x509.ExtKeyUsageMicrosoftServerGatedCrypto,
	"NetscapeServerGatedCrypto":      x509.ExtKeyUsageNetscapeServerGatedCrypto,
	"OCSPSigning":                    x509.ExtKeyUsageOCSPSigning,
	"ServerAuth":                     x509.ExtKeyUsageServerAuth,
	"TimeStamping":                   x509.ExtKeyUsageTimeStamping,
}
View Source
var KeyUsages = map[string]x509.KeyUsage{
	"CRLSign":           x509.KeyUsageCRLSign,
	"CertSign":          x509.KeyUsageCertSign,
	"ContentCommitment": x509.KeyUsageContentCommitment,
	"DataEncipherment":  x509.KeyUsageDataEncipherment,
	"DecipherOnly":      x509.KeyUsageDecipherOnly,
	"DigitalSignature":  x509.KeyUsageDigitalSignature,
	"EncipherOnly":      x509.KeyUsageEncipherOnly,
	"KeyAgreement":      x509.KeyUsageKeyAgreement,
	"KeyEncipherment":   x509.KeyUsageKeyEncipherment,
}
View Source
var PublicKeyAlgorithms = []x509.PublicKeyAlgorithm{
	x509.RSA,
	x509.ECDSA,
	x509.Ed25519,
}

PublicKeyAlgorithms which are supported to create x509 certificates

Functions

func CreateCertificate added in v0.1.0

func CreateCertificate(cert, signCert *x509.Certificate, signKey crypto.PrivateKey) (certDER []byte, privateKey crypto.PrivateKey, err error)

CreateCertificate creates a x509.Certificate and a key with the default key options. See CreateCertificateWithKeyOptions for more details.

func CreateCertificateWithCSR added in v0.1.0

func CreateCertificateWithCSR(csr *x509.CertificateRequest, cert, signCert *x509.Certificate, signKey any) (certDER []byte, err error)

CreateCertificateWithCSR applies the settings from csr and return the signed certificate

func CreateCertificateWithKeyOptions added in v0.1.0

func CreateCertificateWithKeyOptions(cert *x509.Certificate, keyOptions KeyOptions, signCert *x509.Certificate, signKey crypto.PrivateKey) (certDER []byte, privateKey crypto.PrivateKey, err error)

CreateCertificateWithKeyOptions creates a key and certificate. The certificate is signed used signCert and signKey. If signCert or signKey are nil, a self-signed certificate will be created. The certificate and the key are returned PEM encoded.

Example

Create a self-signed certificate with a 4096 bit RSA key

cert := NewServerCertificate("localhost")

keyOptions := KeyOptions{
	Algorithm: x509.RSA,
	Size:      4096,
}

certDER, key, err := CreateCertificateWithKeyOptions(cert, keyOptions, nil, nil)
if err != nil {
	log.Fatal(err)
}

keyPEM, err := EncodeKey(key)
if err != nil {
	log.Fatal(err)
}

certPEM := Encode(certDER)

_, _ = os.Stdout.Write(certPEM)
_, _ = os.Stdout.Write(keyPEM)
Output:

func CreateRequest added in v0.1.0

func CreateRequest(csr *x509.CertificateRequest) (csrPEM []byte, privateKey crypto.PrivateKey, err error)

CreateRequest creates a CSR and a key. The key is created with the default key options. See CreateRequestWithKeyOptions for more details.

func CreateRequestWithKeyOptions added in v0.1.0

func CreateRequestWithKeyOptions(csr *x509.CertificateRequest, keyOptions KeyOptions) (csrPEM []byte, privateKey crypto.PrivateKey, err error)

CreateRequestWithKeyOptions creates a CSR and a key based on key options. The key is created with the default key options.

func Encode

func Encode(derBytes []byte) []byte

Encode encodes DER encoded certificate into PEM encoding

func EncodeCSR

func EncodeCSR(derBytes []byte) []byte

EncodeCSR encodes DER encoded CSR into PEM encoding

func EncodeKey

func EncodeKey(priv any) ([]byte, error)

EncodeKey encodes a *crypto.PrivateKey into PEM encoding by using x509.MarshalPKCS8PrivateKey

func ExtKeyUsageToString

func ExtKeyUsageToString(ku []x509.ExtKeyUsage) string

ExtKeyUsageToString returns a string representation of a []x509.ExtKeyUsage slice

Example
cert := NewClientCertificate("myUser")
usageStr := ExtKeyUsageToString(cert.ExtKeyUsage)
fmt.Println(usageStr)
Output:

ClientAuth

func GenerateKey

func GenerateKey(opts KeyOptions) (crypto.PrivateKey, crypto.PublicKey, error)

GenerateKey returns a private and a public key based on the options. If no PublicKeyAlgorithm is set in the options ECDSA is used. If no key size is set in the options 256 bit is used for ECDSA and 2048 bit for RSA. For ECDSA the following sizes are valid: 224, 256, 384 and 521. For the x509.Ed25519 algorithm the size in the KeyOptions is ignored.

func KeyUsageToString

func KeyUsageToString(bitmask x509.KeyUsage) string

KeyUsageToString returns a string representation of a x509.KeyUsage bitmask

Example
cert := NewCACertificate("My Super Root CA")
usageStr := KeyUsageToString(cert.KeyUsage)
fmt.Println(usageStr)
Output:

CRLSign,CertSign

func KeyUsageToStringSlice added in v0.0.13

func KeyUsageToStringSlice(bitmask x509.KeyUsage) []string

KeyUsageToStringSlice returns a slice with string representations of the x509.KeyUsage bitmask

func Load

func Load(f string) (*x509.Certificate, error)

Load reads a *x509.Certificate from a PEM encoded file.

func LoadCSR

func LoadCSR(f string) (*x509.CertificateRequest, error)

LoadCSR reads a *x509.CertificateRequest from a PEM encoded file.

func LoadKey

func LoadKey(f string) (any, error)

LoadKey reads a *crypto.PrivateKey from a PEM encoded file.

func NewCACertificate

func NewCACertificate(name string) *x509.Certificate

NewCACertificate returns a new certificate. The CommonName is set to name and typical CA certificate settings are set (see SetCAProfile function).

func NewCertificate

func NewCertificate(opts *CertificateOptions) *x509.Certificate

NewCertificate returns a *x509.Certificate with settings set based on CertificateOptions. Further it sets certain defaults if they were not set explicitly: - Expiration one year from now - Random serial number

func NewClientCertificate

func NewClientCertificate(name string) *x509.Certificate

NewClientCertificate returns a new certificate. The CommonName is set to name and typical client certificate settings are set (see SetClientProfile function).

func NewServerCertificate

func NewServerCertificate(name string) *x509.Certificate

NewServerCertificate returns a new certificate. The CommonName is set to name and typical server certificate settings are set (see SetServerProfile function).

func Parse

func Parse(pemData []byte) (*x509.Certificate, error)

Parse returns a *x509.Certificate from PEM encoded data.

func ParseAll added in v0.0.13

func ParseAll(data []byte) ([]*x509.Certificate, error)

ParseAll returns a list of x509.Certificates from a list of concatenated PEM encoded certificates.

func ParseCSR

func ParseCSR(pem []byte) (*x509.CertificateRequest, error)

ParseCSR returns a *x509.CertificateRequest from PEM encoded data.

func ParseKey

func ParseKey(pemData []byte) (key any, err error)

ParseKey returns a *crypto.PrivateKey from PEM encoded data.

func SetCAProfile

func SetCAProfile(cert *x509.Certificate)

SetCAProfile sets typical characteristics of a CA certificate.

func SetClientProfile

func SetClientProfile(cert *x509.Certificate)

SetClientProfile sets typical characteristics of a client certificate.

func SetServerProfile

func SetServerProfile(cert *x509.Certificate)

SetServerProfile sets typical characteristics of a server certificate.

Types

type CertificateOptions added in v0.1.0

type CertificateOptions struct {
	Expiry        time.Duration
	ProfileServer bool
	ProfileClient bool
	ProfileCA     bool

	x509.Certificate
}

CertificateOptions represents all options which can be set using CreateCertificate (see Go docs of it). Further it offers Expiry to set a validity duration instead of absolute times.

type KeyOptions

type KeyOptions struct {
	Algorithm x509.PublicKeyAlgorithm
	Size      int
}

KeyOptions specifies a key algorithm and a size

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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