tls

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2019 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Example
package main

import (
	"log"

	"github.com/liferaft/kubekit/pkg/server/tls"
)

func main() {
	certsDir := "./certificates"
	// Generate the certificates in memory for the CN `kubekit.io`
	ca := tls.GenerateCertificateAuthority("kubekit.io", certsDir)
	// Save them to ./certificates/kubekit.io.{key,crt}
	if err := ca.Persist().Error(); err != nil {
		log.Fatalf("failed to generate the CA certificate. %s", err)
	}

	// Generate a server certificate for the server on `www.server.io` and
	// `192.168.100.10` in memory, sign it with the CA generated and save them
	// to ./certificates/server.{key,crt}
	serverCert := tls.GenerateSignedCertificate("server", certsDir, ca, "www.server.io", "192.168.100.10").Persist()
	if err := serverCert.Error(); err != nil {
		log.Fatalf("failed to generate the server certificate. %s", err)
	}

	// Generate a client certificate for `localhost` in memory, sign it with the CA
	// generated and save them to ./certificates/client.{key,crt}
	clientCert := tls.GenerateSignedClientCertificate("client", certsDir, ca, "www.server.io", "192.168.100.10").Persist()
	if err := clientCert.Error(); err != nil {
		log.Fatalf("failed to generate the server certificate. %s", err)
	}

	// Generate a self signed sertificate in memory and save it to
	// ./certificates/sscert.{key,crt}
	// 	selfSignCert := tls.GenerateSelfSignedCertificate("sscert", certsDir).Persist()
	// 	if err := selfSignCert.Error(); err != nil {
	// 		log.Fatalf("failed to generate the self signed certificate. %s", err)
	// 	}
}
Output:

Example (Options)
package main

import (
	"log"

	"github.com/liferaft/kubekit/pkg/server/tls"
)

func main() {
	// Loads the existing key, generates the CA certificate from it and save the
	// generated certificate to `./certificates/ca.crt`
	caOpts := tls.CertificateOpts{
		CertsDir: "./certificates",
	}
	ca := tls.NewCertificate("corp.org", &caOpts).ReadPrivateKeyFromFile("/var/pki/ca.key").GenerateCertificateAuthority().WriteCertificateToFile("./certificates/ca.crt")
	if err := ca.Error(); err != nil {
		log.Fatalf("filed to generate the CA certificate. %s", err)
	}

	// Generates and save the server certificate from an existing key to be used on the following domain names
	serverOpts := tls.CertificateOpts{
		CertsDir: "./certificates",
		Bits:     1024,
		DNSNames: []string{"www.server.com", "www.server.io"},
	}
	serverCert := tls.NewCertificate("server", &serverOpts).GenerateCertificate().Persist()
	if err := serverCert.Error(); err != nil {
		log.Fatalf("filed to generate the server certificate. %s", err)
	}

	clientOpts := tls.CertificateOpts{
		CertsDir: "./certificates",
		Bits:     2048,
		UseAs:    tls.CertificateUsedForClient,
	}
	clientCert := tls.NewCertificate("client", &clientOpts).GenerateCertificate().Persist()
	if err := clientCert.Error(); err != nil {
		log.Fatalf("filed to generate the client certificate. %s", err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Certificate

type Certificate struct {
	PrivateKey         *rsa.PrivateKey // Private Key may be included/repeated inside Certificate
	Certificate        *x509.Certificate
	CertificateRequest *x509.CertificateRequest

	Opts *CertificateOpts
	// contains filtered or unexported fields
}

Certificate is a X.509 Key Pair or Certificate that includes the Private Key, Certificate and other useful information about them.

func GenerateCertificate

func GenerateCertificate(cn, certsDir string) *Certificate

GenerateCertificate loads the certificate from the given file if exists, otherwise generate it

func GenerateCertificateAuthority

func GenerateCertificateAuthority(cn, certsDir string) *Certificate

GenerateCertificateAuthority generates a CA contained in a Certificate

Example
package main

import (
	"log"

	"github.com/liferaft/kubekit/pkg/server/tls"
)

func main() {
	kpCA := tls.GenerateCertificateAuthority("ca", "/tmp/example").Persist()

	if err := kpCA.Error(); err != nil {
		log.Fatalf("failed to save the CA key/cert files. %s", err)
	}
}
Output:

func GenerateCertificateSigningRequest

func GenerateCertificateSigningRequest(cn, certDir string, altNames ...string) *Certificate

GenerateCertificateSigningRequest generates a CSR to be used to sign the certificate with a CA

func GenerateSignedCertificate

func GenerateSignedCertificate(cn, certsDir string, ca *Certificate, altNames ...string) *Certificate

GenerateSignedCertificate create and signs a certificate with the given CA certificate

func GenerateSignedClientCertificate

func GenerateSignedClientCertificate(cn, certsDir string, ca *Certificate, altNames ...string) *Certificate

GenerateSignedClientCertificate create and signs a certificate to be used by a client with the given CA certificate

func Load

func Load(cn, keyFilename, certFilename string) *Certificate

Load loads the private key and certificate from the given files to create a Certificate

func LoadFromDir

func LoadFromDir(cn, certsDir string) *Certificate

LoadFromDir loads the private key and certificate from the given certificates directory to create a Certificate. The filenames should be `certsDir/name.key` and `certsDir/name.crt`

func NewCertificate

func NewCertificate(cn string, opts *CertificateOpts) *Certificate

NewCertificate creates an empty Certificate

func (*Certificate) CertificatePEM

func (crt *Certificate) CertificatePEM() []byte

CertificatePEM returns the PEM encode of the certificate

func (*Certificate) CertificateSigningRequestPEM

func (crt *Certificate) CertificateSigningRequestPEM() []byte

CertificateSigningRequestPEM returns the PEM encode of the CSR

func (*Certificate) Error

func (crt *Certificate) Error() error

Error returns the latest occured error

func (*Certificate) GenerateCertificate

func (crt *Certificate) GenerateCertificate() *Certificate

GenerateCertificate generates the certificate from the existing private key

func (*Certificate) GenerateCertificateAuthority

func (crt *Certificate) GenerateCertificateAuthority() *Certificate

GenerateCertificateAuthority generates a CA certificate and private key from the given options (filenames, passphrase, etc..)

Example (PrivateKeyFromPEM)
package main

import (
	"io/ioutil"
	"log"
	"os"

	"github.com/liferaft/kubekit/pkg/server/tls"
)

func main() {
	// generate this CA PEM with:
	// openssl genrsa -des3 -passout pass:Test1ng 1024 2>/dev/null
	caPEM := []byte(`-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,32DE7AED71E4F727

ZqmUAYaFOmSbT/yr8rvHI3hQVQ9oqtHyV5mLNfYYRkOCwYgo3ZbBnIMNTPHMrsb7
8X8YAkpan/g0K0ftN7j0ajXkOlDN6BBOKqDoXPBu+pxNixgGpC63wJSAu+undzW8
Oigj/Vlv//yM5X699UNawGMD++geOAyvwO5QFX4OvvnCi+eCmCuAp28j6xHk8BMV
MiXznogl2KLUBYDINKajBwIU0n2todxJwDWmADaCK29hDg26pMFrDrVE67LzyHMH
NZaKjWaVwLzfW1Xf8vuO4vNMJjlTvhLGuMX+O5fln1nt9Af/HsIqod2BGvZKJGGn
HMxuj0I/rKJE/brpYW0dOENKKMfeoeZ58Zv1xTffOj78NAMwceNyIWViVR/iu/6p
7eFR/e/Ia2iH1oKyBKaGhIuoGx+Sz7bwD2OmKGnFS8km+Pq2V3uQnWFvhSMIZGd+
BOvU9re9H++j9aMQPUQCU0lH6AaZlB4wdPNqC+KJ3NoSz77tYLwvkfCFnn9uksuF
fZl/RUsK8zAGqULeT49IFG96Jqbv3rgeRLbmnD/QFtUUBnVX3gsGgBxdzW9zQ3/1
vg6Q1XW1LL3I+86gCCRimmMRSyeSsximN7jLzJqwJf0WYFrvl55uO9GqvVfGnWIF
M3PuQprkT/NUkZZ0AzuZRnHL42fuLuIIoeQg+TaC/wiMpWQLT3x1Mi2p50RN9Bjg
fuFAZNrlvx4IzbUxttFlaX7pfdBvPm+7T8DY9Rm6+IUI1Sdq09q/jtaXGynJM1tM
t4gsOW4mBarSMTyglY7cW1lN6nFyyuhT+bzqRHhu8DxvZulFSpYhgA==
-----END RSA PRIVATE KEY-----`)

	kpCA := tls.NewCertificate("example", nil).GeneratePrivateKeyFromPEM(caPEM).GenerateCertificateAuthority()

	tmpCACertFile, _ := ioutil.TempFile("", "example")
	caCertFilename := tmpCACertFile.Name() + ".crt"
	defer os.Remove(caCertFilename)

	if err := kpCA.WriteCertificateToFile(caCertFilename).Error(); err != nil {
		log.Fatalf("failed to save the CA cert file to %q. %s", caCertFilename, err)
	}
}
Output:

Example (ReadPrivateKeyFromFile)
package main

import (
	"fmt"

	"github.com/liferaft/kubekit/pkg/server/tls"
)

func main() {
	// generate the CA key with:
	// openssl genrsa -des3 -passout pass:Test1ng -out /tmp/example/ca.key 1024
	kpCA := tls.NewCertificate("example", nil).WithPassphrase("Test1ng").ReadPrivateKeyFromFile("/tmp/example/ca.key").GenerateCertificateAuthority()

	certPEMBytes := kpCA.CertificatePEM()
	fmt.Println(string(certPEMBytes))
}
Output:

Example (WithBits)
package main

import (
	"io/ioutil"
	"log"
	"os"

	"github.com/liferaft/kubekit/pkg/server/tls"
)

func main() {
	kpCA := tls.NewCertificate("example", nil).WithBits(2048).GenerateCertificateAuthority()
	if err := kpCA.Error(); err != nil {
		log.Fatalf("failed to generate the CA with 2046 bits. %s", err)
	}

	tmpCAKeyFile, _ := ioutil.TempFile("", "example")
	caKeyFilename := tmpCAKeyFile.Name() + ".key"
	defer os.Remove(caKeyFilename)
	tmpCACertFile, _ := ioutil.TempFile("", "example")
	caCertFilename := tmpCACertFile.Name() + ".crt"
	defer os.Remove(caCertFilename)

	kpCA.WriteToFiles(caKeyFilename, caCertFilename)
	if err := kpCA.Error(); err != nil {
		log.Fatalf("failed to save the CA key/cert files to %q and %q. %s", caKeyFilename, caCertFilename, err)
	}
}
Output:

func (*Certificate) GenerateCertificateFromPEM

func (crt *Certificate) GenerateCertificateFromPEM(data []byte) *Certificate

GenerateCertificateFromPEM ?

func (*Certificate) GenerateCertificateSigningRequest

func (crt *Certificate) GenerateCertificateSigningRequest() *Certificate

GenerateCertificateSigningRequest generates a CSR to be used to sign the certificate with a CA

func (*Certificate) GeneratePrivateKeyFromPEM

func (crt *Certificate) GeneratePrivateKeyFromPEM(data []byte) *Certificate

GeneratePrivateKeyFromPEM generates a Key Pair from the given private key PEM data

func (*Certificate) GenerateRSAKey

func (crt *Certificate) GenerateRSAKey() *Certificate

GenerateRSAKey generates an RSA Private Key for the given size in the options

func (*Certificate) GenerateSignedCertificate

func (crt *Certificate) GenerateSignedCertificate(ca *Certificate) *Certificate

GenerateSignedCertificate create and signs a certificate with the given CA certificate

func (*Certificate) GetPrivateKey

func (crt *Certificate) GetPrivateKey() *Certificate

GetPrivateKey loads the private key from the given file if exists, otherwise generates a RSA key

func (*Certificate) Load

func (crt *Certificate) Load() *Certificate

Load loads the Key Pair from the files in the opts

func (*Certificate) Persist

func (crt *Certificate) Persist() *Certificate

Persist make the keys persistents, store them into the filenames defined in the options or in the certificates directory

func (*Certificate) PrivateKeyPEM

func (crt *Certificate) PrivateKeyPEM() []byte

PrivateKeyPEM returns the private key in PEM format. It will be encrypted if the passphrase is defined in the options

func (*Certificate) ReadCertificateFile

func (crt *Certificate) ReadCertificateFile() *Certificate

ReadCertificateFile loads the certificate from the certificate file defined in the options

func (*Certificate) ReadCertificateFromFile

func (crt *Certificate) ReadCertificateFromFile(filename string) *Certificate

ReadCertificateFromFile generates a Certificate from the given certificate file

func (*Certificate) ReadFromFile

func (crt *Certificate) ReadFromFile(keyFilename, certFilename string) *Certificate

ReadFromFile reads the Private Key and Certificate to the given files

func (*Certificate) ReadPrivateKeyFile

func (crt *Certificate) ReadPrivateKeyFile() *Certificate

ReadPrivateKeyFile loads the private key from the key file defined in the options

func (*Certificate) ReadPrivateKeyFromFile

func (crt *Certificate) ReadPrivateKeyFromFile(filename string) *Certificate

ReadPrivateKeyFromFile generates a Key Pair from the given private key file

func (*Certificate) Sign

func (crt *Certificate) Sign(ca *Certificate) *Certificate

Sign signs the current certificate with the given CA certificate

func (*Certificate) WithBits

func (crt *Certificate) WithBits(bits int) *Certificate

WithBits assign the number of bits to generate the RSA Private Key. If zero sets the default value

func (*Certificate) WithPassphrase

func (crt *Certificate) WithPassphrase(passphrase string) *Certificate

WithPassphrase assigns the given password to the Key Pair that is used to open encrypted key files

func (*Certificate) WithPath

func (crt *Certificate) WithPath(certsDir string) *Certificate

WithPath append the certificates diretory into the Certificate options

func (*Certificate) WriteCertificate

func (crt *Certificate) WriteCertificate() *Certificate

WriteCertificate saves the certificate to the certificate file defined in the options

func (*Certificate) WriteCertificateToFile

func (crt *Certificate) WriteCertificateToFile(filename string) *Certificate

WriteCertificateToFile writes the certificate to the given filename

func (*Certificate) WritePrivateKeyFile

func (crt *Certificate) WritePrivateKeyFile() *Certificate

WritePrivateKeyFile saves the private key to the key file defined in the options

func (*Certificate) WritePrivateKeyToFile

func (crt *Certificate) WritePrivateKeyToFile(filename string) *Certificate

WritePrivateKeyToFile saves the private key to the given file

func (*Certificate) WriteToFiles

func (crt *Certificate) WriteToFiles(keyFilename, certFilename string) *Certificate

WriteToFiles save the Private Key and Certificate to the given files

type CertificateOpts

type CertificateOpts struct {
	CommonName         string
	CertsDir           string
	CertificateFile    string
	PrivateKeyFile     string
	Passphrase         string
	Bits               int
	Organization       string
	OrganizationalUnit string
	Locality           string
	Province           string
	Country            string
	Duration           time.Duration
	DNSNames           []string
	IPAddresses        []string
	URIs               []string
	UseAs              CertificateUse
}

CertificateOpts contain the options to create the Certificate struct

func DefaultCertificateOpts

func DefaultCertificateOpts(cn, certsDir string) *CertificateOpts

DefaultCertificateOpts creates a CertificateOpts with default values

func (*CertificateOpts) AsCA

func (opts *CertificateOpts) AsCA() *CertificateOpts

AsCA changes the use of the Certificate to CA

func (*CertificateOpts) AsClient

func (opts *CertificateOpts) AsClient() *CertificateOpts

AsClient changes the use of the Certificate to client

func (*CertificateOpts) AsServer

func (opts *CertificateOpts) AsServer() *CertificateOpts

AsServer changes the use of the Certificate to server

func (*CertificateOpts) GenerateCSRTemplate

func (opts *CertificateOpts) GenerateCSRTemplate() (x509.CertificateRequest, error)

GenerateCSRTemplate generates a x509 CertificateRequest template from the given options

func (*CertificateOpts) GenerateSubject

func (opts *CertificateOpts) GenerateSubject() pkix.Name

GenerateSubject generates the subject (pkix.Name) required to generate certificate templates

func (*CertificateOpts) GenerateSubjectAltNameExtension

func (opts *CertificateOpts) GenerateSubjectAltNameExtension() (*pkix.Extension, error)

GenerateSubjectAltNameExtension generates the SAN extension for the template certificate

func (*CertificateOpts) GenerateTemplate

func (opts *CertificateOpts) GenerateTemplate() (x509.Certificate, error)

GenerateTemplate generates a x509 Certificate template from the given options

func (*CertificateOpts) IsCertFileFound

func (opts *CertificateOpts) IsCertFileFound() bool

IsCertFileFound returns true if the certificate file is found or accesible

func (*CertificateOpts) IsKeyFileFound

func (opts *CertificateOpts) IsKeyFileFound() bool

IsKeyFileFound returns true if the private key file is found or accesible

func (*CertificateOpts) WithPath

func (opts *CertificateOpts) WithPath(certsDir string) *CertificateOpts

WithPath sets the certificate directory and assign the private key file and certificate file if not valid

type CertificateUse

type CertificateUse int

CertificateUse is to specify what's the use of the certificate

const (
	CertificateUsedForCA     CertificateUse = 1 << iota // 0001 = 1
	CertificateUsedForClient                            // 0010 = 2
)

CA, Server, Client are the different uses for a certificate

Jump to

Keyboard shortcuts

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