all repos — flounder @ 58a76b756308ca8920f3091d35caf8220605f3da

A small site builder for the Gemini protocol

cert.go (view raw)

 1package main
 2
 3import (
 4	"crypto"
 5	"crypto/tls"
 6	"crypto/x509"
 7	"encoding/pem"
 8	"io"
 9	"os"
10)
11
12// writeCertificate writes the provided certificate and private key
13// to path.crt and path.key respectively.
14func writeCertificate(path string, cert tls.Certificate) error {
15	// Write the certificate
16	crtPath := path + ".crt"
17	crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
18	if err != nil {
19		return err
20	}
21	if err := marshalX509Certificate(crtOut, cert.Leaf.Raw); err != nil {
22		return err
23	}
24
25	// Write the private key
26	keyPath := path + ".key"
27	keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
28	if err != nil {
29		return err
30	}
31	return marshalPrivateKey(keyOut, cert.PrivateKey)
32}
33
34// marshalX509Certificate writes a PEM-encoded version of the given certificate.
35func marshalX509Certificate(w io.Writer, cert []byte) error {
36	return pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: cert})
37}
38
39// marshalPrivateKey writes a PEM-encoded version of the given private key.
40func marshalPrivateKey(w io.Writer, priv crypto.PrivateKey) error {
41	privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
42	if err != nil {
43		return err
44	}
45	return pem.Encode(w, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
46}