aboutsummaryrefslogtreecommitdiff
path: root/crypto.go
blob: c8fc6562bbeb11aeedaa695f9d0c35e82a792e50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package acme

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/base64"
	"encoding/pem"
	"io"
	"io/ioutil"
	"os"
	"path"
)

func LoadKeyFile(fname string) (*rsa.PrivateKey, error) {
	fd, err := os.Open(fname)
	if err != nil {
		return nil, err
	}
	defer fd.Close()
	return LoadKey(fd)
}

func LoadKey(r io.Reader) (*rsa.PrivateKey, error) {
	der, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(der)
	return x509.ParsePKCS1PrivateKey(block.Bytes)
}

func NewKey(w io.Writer, size int) (*rsa.PrivateKey, error) {
	key, err := rsa.GenerateKey(rand.Reader, size)
	if err != nil {
		return nil, err
	}
	return key, SaveKey(w, key)
}

func SaveKey(w io.Writer, key *rsa.PrivateKey) error {
	block := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	}
	return pem.Encode(w, block)
}

func NewCSR(altnames []string, key *rsa.PrivateKey) (string, error) {
	tmpl := x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName: altnames[0],
		},
	}
	if len(altnames) > 1 {
		tmpl.DNSNames = altnames
	}
	der, err := x509.CreateCertificateRequest(rand.Reader, &tmpl, key)
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(der), nil
}

func SaveCert(w io.Writer, crt []*x509.Certificate) error {
	for _, c := range crt {
		block := &pem.Block{
			Type:  "CERTIFICATE",
			Bytes: c.Raw,
		}
		if err := pem.Encode(w, block); err != nil {
			return err
		}
	}
	return nil
}

func LoadCertFile(fname string) ([]*x509.Certificate, error) {
	fd, err := os.Open(fname)
	if err != nil {
		return nil, err
	}
	defer fd.Close()
	return LoadCert(fd)
}

func LoadCert(r io.Reader) ([]*x509.Certificate, error) {
	der, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(der)
	return x509.ParseCertificates(block.Bytes)
}

func CreateKeyFile(fname string) (io.WriteCloser, error) {
	return createFile(fname, 0700)
}

func CreateCertFile(fname string) (io.WriteCloser, error) {
	return createFile(fname, 0755)
}

func createFile(fname string, mode os.FileMode) (io.WriteCloser, error) {
	if err := os.MkdirAll(path.Dir(fname), mode); err != nil {
		return nil, err
	}
	flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
	return os.OpenFile(fname, flags, mode&0644)
}