cert4now

package module
v0.0.0-...-bcff5f3 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2022 License: Apache-2.0 Imports: 21 Imported by: 2

README

Certificate for now

GoDoc

Purpose

Easily generate a certificate for the time being, usable on a TLS-enabled server.

Example

Generating a self signed certificate, then saving it into file.
cert, _ := cert4now.Generate()
cert4now.WritePrivateKeyFile("cert.key", cert, 0600)
cert4now.WriteCertificateFile("cert.crt", cert, 0644)
Generating a root CA, an intermediate CA and a leaf certificate.
rootCA, _ := cert4now.Generate(
	cert4now.CommonName("My Root CA"),
	cert4now.AddDate(20, 0, 0),
	cert4now.KeyUsage(x509.KeyUsageDigitalSignature|x509.KeyUsageCertSign|x509.KeyUsageCRLSign),
	cert4now.ExtKeyUsage(),
	cert4now.IsCA(true),
)

ca, _ := cert4now.Generate(
	cert4now.Authority(rootCA),
	cert4now.CommonName("My CA"),
	cert4now.AddDate(20, 0, 0),
	cert4now.KeyUsage(x509.KeyUsageDigitalSignature|x509.KeyUsageCertSign|x509.KeyUsageCRLSign),
	cert4now.ExtKeyUsage(),
	cert4now.IsCA(true),
)

cert, _ := cert4now.Generate(
	cert4now.Authority(ca),
	cert4now.CommonName("www.example.com"),
	cert4now.IsCA(false),
)

Documentation

Overview

Package cert4now provides functions to generate tls.Certificate.

Example
// Generating a self signed certificate as a CA.
ca, err := cert4now.Generate(
	cert4now.CommonName("Root CA"),
	cert4now.AddDate(20, 0, 0),
	cert4now.KeyUsage(x509.KeyUsageDigitalSignature|x509.KeyUsageCertSign|x509.KeyUsageCRLSign),
	cert4now.ExtKeyUsage(),
	cert4now.IsCA(true),
)
if err != nil {
	panic(err)
}

ln, err := net.Listen("tcp", "127.0.0.1:")
if err != nil {
	panic(err)
}
defer ln.Close()

server := func() (exec func() error, intr func(error)) {
	// Generating a certificate signed by CA for the TLS-enabled http server.
	cert, err := cert4now.Generate(
		cert4now.Authority(ca),
		cert4now.CommonName("Leaf certificate"),
		cert4now.Names("localhost", "127.0.0.1"),
		cert4now.IsCA(false),
	)
	if err != nil {
		panic(err)
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "hello world")
	})

	srv := http.Server{
		TLSConfig: &tls.Config{
			Certificates: []tls.Certificate{cert},
		},
	}

	exec = func() error {
		return srv.ServeTLS(ln, "", "")
	}

	intr = func(error) {
		ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
		_ = srv.Shutdown(ctx)
		cancel()
	}

	return
}

client := func() (exec func() error, intr func(error)) {
	exec = func() error {
		ca, err := x509.ParseCertificate(ca.Certificate[0])
		if err != nil {
			return err
		}
		rootCAs := x509.NewCertPool()
		rootCAs.AddCert(ca)

		client := &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					RootCAs: rootCAs,
					VerifyPeerCertificate: func(_ [][]byte, verifiedChains [][]*x509.Certificate) error {
						for i, x := range verifiedChains {
							for j, y := range x {
								fmt.Println(i, j, y.Subject.CommonName)
							}
						}
						return nil
					},
				},
			},
		}

		resp, err := client.Get("https://" + ln.Addr().String())
		if err != nil {
			return err
		}
		p, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		resp.Body.Close()

		fmt.Println(string(p))
		return nil
	}

	intr = func(error) {}
	return
}

var g run.Group
g.Add(server())
g.Add(client())
if err := g.Run(); err != nil {
	panic(err)
}
Output:

0 0 Leaf certificate
0 1 Root CA
hello world

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidAuthorityKey = errors.New("authority's PrivateKey is not type of crypto.Signer")

ErrInvalidAuthorityKey represents the authority certificate has an invalid private key.

Functions

func EncodeCertificateToPEM

func EncodeCertificateToPEM(cert tls.Certificate) ([]byte, error)

EncodeCertificateToPEM encode the certificate of cert into PEM format.

func EncodePrivateKeyToPEM

func EncodePrivateKeyToPEM(cert tls.Certificate) ([]byte, error)

EncodePrivateKeyToPEM encodes the private key of cert into PEM format.

func Generate

func Generate(options ...Option) (cert tls.Certificate, err error)

Generate generates a new certificate.

func WriteCertificate

func WriteCertificate(w io.Writer, cert tls.Certificate) error

WriteCertificate writes the certificate into w in PEM format.

func WriteCertificateFile

func WriteCertificateFile(filename string, cert tls.Certificate, perm fs.FileMode) error

WriteCertificateFile writes the certificate into the file of filename in PEM format.

func WritePrivateKey

func WritePrivateKey(w io.Writer, cert tls.Certificate) error

WritePrivateKey writes the private key into w in PEM format.

func WritePrivateKeyFile

func WritePrivateKeyFile(filename string, cert tls.Certificate, perm fs.FileMode) error

WritePrivateKeyFile writes the private key into the file of filename in PEM format.

Types

type Option

type Option func(*param)

Option represents an option for generating a certificate.

func AddDate

func AddDate(years, months, days int) Option

AddDate returns an option of setting the NotAfter, and NotBefore in some case.

func Authority

func Authority(cert tls.Certificate) Option

Authority returns an option of setting the authority.

func BasicConstraintsValid

func BasicConstraintsValid(flag bool) Option

BasicConstraintsValid returns an option of setting the BasicConstraintsValid.

func CommonName

func CommonName(name string) Option

CommonName returns an option of setting the common name.

func DNSNames

func DNSNames(names ...string) Option

DNSNames returns an option of appending the DNSNames.

func DNSNamesReset

func DNSNamesReset(names ...string) Option

DNSNamesReset returns an option of setting the DNSNames.

func ECDSA

func ECDSA(c elliptic.Curve) Option

ECDSA returns an option of generating then setting the private key.

func EmailAddresses

func EmailAddresses(emails ...string) Option

EmailAddresses returns an option of appending the EmailAddresses.

func EmailAddressesReset

func EmailAddressesReset(emails ...string) Option

EmailAddressesReset returns an option of setting the EmailAddresses.

func ExtKeyUsage

func ExtKeyUsage(usage ...x509.ExtKeyUsage) Option

ExtKeyUsage returns an option of setting an ExtKeyUsage.

func IPAddresses

func IPAddresses(ips ...net.IP) Option

IPAddresses returns an option of appending the IPAddresses.

func IPAddressesReset

func IPAddressesReset(ips ...net.IP) Option

IPAddressesReset returns an option of setting the IPAddresses.

func IsCA

func IsCA(isCA bool) Option

IsCA returns an option of setting the IsCA and BasicConstraintsValid.

func KeyUsage

func KeyUsage(usage x509.KeyUsage) Option

KeyUsage returns an option of setting the KeyUsage.

func Names

func Names(names ...string) Option

Names returns an option of appending DNSNames and IPAddresses. For each of names, the name that success to net.ParseIP is appended to IPAddresses. The name that failed to net.ParseIP is appended to DNSNames.

func NotAfter

func NotAfter(t time.Time) Option

NotAfter returns an option of setting the NotAfter.

func NotBefore

func NotBefore(t time.Time) Option

NotBefore returns an option of setting the NotBefore.

func RSA

func RSA(bits int) Option

RSA returns an option of generating then setting the private key.

func SerialNumber

func SerialNumber(serialNumber *big.Int) Option

SerialNumber returns an option of setting the serial number.

func Signer

func Signer(signer crypto.Signer) Option

Signer returns an option of setting the private key.

func Subject

func Subject(name pkix.Name) Option

Subject returns an option of setting the subject.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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