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
|
package main
import (
"crypto"
"crypto/tls"
"crypto/x509"
"io"
"os"
"path"
"dim13.org/acme"
)
func NewFile(fname string, mode os.FileMode) (io.WriteCloser, error) {
_ = os.Rename(fname, fname+".bak")
flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
return os.OpenFile(fname, flags, mode)
}
func saveKey(fname string, key crypto.PrivateKey) error {
if err := os.MkdirAll(path.Dir(fname), 0700); err != nil {
return err
}
fd, err := NewFile(fname, 0600)
if err != nil {
return err
}
defer fd.Close()
return acme.SaveKey(fd, key)
}
func saveCrt(fname string, certs [][]byte) error {
if err := os.MkdirAll(path.Dir(fname), 0755); err != nil {
return err
}
fd, err := NewFile(fname, 0644)
if err != nil {
return err
}
defer fd.Close()
for _, crt := range certs {
if err := acme.SaveCert(fd, crt); err != nil {
return err
}
}
return nil
}
func (d domain) Save(cert tls.Certificate) error {
if err := saveKey(d.KeyFile, cert.PrivateKey); err != nil {
return err
}
if err := saveCrt(d.CrtFile, cert.Certificate); err != nil {
return err
}
return nil
}
func (d domain) Load() (tls.Certificate, error) {
crt, err := tls.LoadX509KeyPair(d.CrtFile, d.KeyFile)
if err != nil {
return tls.Certificate{}, err
}
crt.Leaf, err = x509.ParseCertificate(crt.Certificate[0])
return crt, err
}
func (a account) Save(key crypto.PrivateKey) error {
if err := os.MkdirAll(path.Dir(a.KeyFile), 0700); err != nil {
return err
}
fd, err := NewFile(a.KeyFile, 0600)
if err != nil {
return err
}
defer fd.Close()
return acme.SaveKey(fd, key)
}
func (a account) Load() (crypto.PrivateKey, error) {
fd, err := os.Open(a.KeyFile)
if err != nil {
return nil, err
}
defer fd.Close()
return acme.LoadKey(fd)
}
|