-
Notifications
You must be signed in to change notification settings - Fork 0
/
cert.go
103 lines (98 loc) · 2.54 KB
/
cert.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
100
101
102
103
package mitm
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"time"
)
const (
caMaxAge = 5 * 365 * 24 * time.Hour
leafMaxAge = 24 * time.Hour
caUsage = x509.KeyUsageDigitalSignature |
x509.KeyUsageContentCommitment |
x509.KeyUsageKeyEncipherment |
x509.KeyUsageDataEncipherment |
x509.KeyUsageKeyAgreement |
x509.KeyUsageCertSign |
x509.KeyUsageCRLSign
leafUsage = caUsage
)
func genCert(ca *tls.Certificate, names []string) (*tls.Certificate, error) {
now := time.Now().Add(-1 * time.Hour).UTC()
if !ca.Leaf.IsCA {
return nil, errors.New("CA cert is not a CA")
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, fmt.Errorf("failed to generate serial number: %s", err)
}
tmpl := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{CommonName: names[0]},
NotBefore: now,
NotAfter: now.Add(leafMaxAge),
KeyUsage: leafUsage,
BasicConstraintsValid: true,
DNSNames: names,
SignatureAlgorithm: x509.ECDSAWithSHA512,
}
key, err := genKeyPair()
if err != nil {
return nil, err
}
x, err := x509.CreateCertificate(rand.Reader, tmpl, ca.Leaf, key.Public(), ca.PrivateKey)
if err != nil {
return nil, err
}
cert := new(tls.Certificate)
cert.Certificate = append(cert.Certificate, x)
cert.PrivateKey = key
cert.Leaf, _ = x509.ParseCertificate(x)
return cert, nil
}
func genKeyPair() (*ecdsa.PrivateKey, error) {
return ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
}
func GenCA(name string) (certPEM, keyPEM []byte, err error) {
now := time.Now().UTC()
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: name},
NotBefore: now,
NotAfter: now.Add(caMaxAge),
KeyUsage: caUsage,
BasicConstraintsValid: true,
IsCA: true,
MaxPathLen: 2,
SignatureAlgorithm: x509.ECDSAWithSHA512,
}
key, err := genKeyPair()
if err != nil {
return
}
certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
if err != nil {
return
}
keyDER, err := x509.MarshalECPrivateKey(key)
if err != nil {
return
}
certPEM = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certDER,
})
keyPEM = pem.EncodeToMemory(&pem.Block{
Type: "ECDSA PRIVATE KEY",
Bytes: keyDER,
})
return
}