-
Notifications
You must be signed in to change notification settings - Fork 12
/
generate_certs.go
91 lines (78 loc) · 2.25 KB
/
generate_certs.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
package cert
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
"github.com/pkg/errors"
)
const (
FilePermission os.FileMode = 0644
caBitSize = 4096
OrgName = "Intelops"
RootCACommonName = "Capten Agent Root CA"
ClusterCACertSecretName = "agent-ca-cert"
CertManagerNamespace = "cert-manager"
)
type Key struct {
Key *rsa.PrivateKey
KeyData []byte
}
type Cert struct {
Cert *x509.Certificate
CertData []byte
}
type CertificatesData struct {
RootKey *Key
RootCert *Cert
CaChainCertData []byte
}
func GenerateRootCerts() (*CertificatesData, error) {
rootKey, rootCertTemplate, err := generateCACert()
if err != nil {
return nil, err
}
return &CertificatesData{
RootKey: rootKey,
RootCert: rootCertTemplate,
CaChainCertData: rootCertTemplate.CertData,
}, nil
}
func generateCACert() (*Key, *Cert, error) { //(rootKey *rsa.PrivateKey, rootCertTemplate *x509.Certificate, err error) {
rootKey, err := rsa.GenerateKey(rand.Reader, caBitSize)
if err != nil {
err = errors.WithMessage(err, "failed to generate RSA key for root certificate")
return nil, nil, err
}
rootCertTemplate := &x509.Certificate{
Subject: pkix.Name{
Organization: []string{OrgName},
CommonName: RootCACommonName,
},
SerialNumber: big.NewInt(1),
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(5, 0, 0),
IsCA: true,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
rootCert, err := x509.CreateCertificate(rand.Reader, rootCertTemplate, rootCertTemplate, &rootKey.PublicKey, rootKey)
if err != nil {
err = errors.WithMessage(err, "failed to create root CA certificate")
return nil, nil, err
}
rootCertPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootCert})
rootKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rootKey)})
return &Key{
Key: rootKey,
KeyData: rootKeyPEM,
},
&Cert{
Cert: rootCertTemplate,
CertData: rootCertPEM,
}, nil
}