This repository has been archived by the owner on Nov 20, 2021. It is now read-only.
/
pki.go
80 lines (71 loc) · 1.79 KB
/
pki.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
package pki
import (
"crypto"
"crypto/x509"
"path/filepath"
"github.com/pkg/errors"
)
type KeyPair struct {
Name string
Cert *x509.Certificate
Key crypto.Signer
}
func (k *KeyPair) WriteFiles(dir string) error {
return WriteCertAndKey(dir, k.Name, k.Cert, k.Key)
}
func LoadKeyPair(path, name string) (*KeyPair, error) {
cert, err := ReadCertFromFile(filepath.Join(path, name+".crt"))
if err != nil {
return nil, err
}
key, err := ReadKeyFromFile(filepath.Join(path, name+".key"))
if err != nil {
return nil, err
}
kp := &KeyPair{
Name: name,
Cert: cert,
Key: key,
}
return kp, nil
}
type CertificateAuthority struct {
*KeyPair
}
func NewCertificateAuthority(name string, cfg *Config) (*CertificateAuthority, error) {
key, err := NewPrivateKey()
if err != nil {
return nil, errors.Wrap(err, "unable to create private key while generating CA certificate")
}
cert, err := NewSelfSignedCACert(cfg, key)
if err != nil {
return nil, errors.Wrap(err, "unable to create self-signed CA certificate")
}
ca := &CertificateAuthority{
KeyPair: &KeyPair{
Name: name,
Cert: cert,
Key: key,
},
}
return ca, nil
}
// NewSignedKeyPair returns a new KeyPair signed by the CA.
func (c *CertificateAuthority) NewSignedKeyPair(name string, cfg *Config) (*KeyPair, error) {
key, err := NewPrivateKey()
if err != nil {
return nil, errors.Wrap(err, "unable to create private key")
}
cert, err := NewSignedCert(cfg, key, c.Cert, c.Key)
if err != nil {
return nil, errors.Wrap(err, "unable to sign certificate")
}
return &KeyPair{Name: name, Cert: cert, Key: key}, nil
}
func LoadCertificateAuthority(path, name string) (*CertificateAuthority, error) {
kp, err := LoadKeyPair(path, name)
if err != nil {
return nil, err
}
return &CertificateAuthority{KeyPair: kp}, nil
}