-
Notifications
You must be signed in to change notification settings - Fork 796
/
ca.go
99 lines (82 loc) · 2.32 KB
/
ca.go
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
package ca
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
"github.com/cortexproject/cortex/pkg/util/runutil"
)
type CA struct {
key *ecdsa.PrivateKey
cert *x509.Certificate
serial *big.Int
}
func New(name string) *CA {
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
panic(err)
}
return &CA{
key: key,
cert: &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{name},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 180),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
IsCA: true,
},
serial: big.NewInt(2),
}
}
func writeExclusivePEMFile(path, marker string, mode os.FileMode, data []byte) (err error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
return err
}
defer runutil.CloseWithErrCapture(&err, f, "write pem file")
if err := pem.Encode(f, &pem.Block{Type: marker, Bytes: data}); err != nil {
return err
}
return nil
}
func (ca *CA) WriteCACertificate(path string) error {
derBytes, err := x509.CreateCertificate(rand.Reader, ca.cert, ca.cert, ca.key.Public(), ca.key)
if err != nil {
return err
}
return writeExclusivePEMFile(path, "CERTIFICATE", 0644, derBytes)
}
func (ca *CA) WriteCertificate(template *x509.Certificate, certPath string, keyPath string) error {
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return err
}
keyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
if err := writeExclusivePEMFile(keyPath, "PRIVATE KEY", 0600, keyBytes); err != nil {
return err
}
template.IsCA = false
template.NotBefore = time.Now()
if template.NotAfter.IsZero() {
template.NotAfter = time.Now().Add(time.Hour * 24 * 180)
}
template.SerialNumber = ca.serial.Add(ca.serial, big.NewInt(1))
derBytes, err := x509.CreateCertificate(rand.Reader, template, ca.cert, key.Public(), ca.key)
if err != nil {
return err
}
return writeExclusivePEMFile(certPath, "CERTIFICATE", 0644, derBytes)
}