-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_ca.go
More file actions
80 lines (69 loc) · 1.68 KB
/
Copy pathinit_ca.go
File metadata and controls
80 lines (69 loc) · 1.68 KB
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 main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
"github.com/AdguardTeam/golibs/log"
)
const (
certPath = "ca.crt"
keyPath = "ca.key"
)
func init() {
_, certErr := os.Stat(certPath)
_, keyErr := os.Stat(keyPath)
if !os.IsNotExist(certErr) && !os.IsNotExist(keyErr) {
return
}
log.Info("Generating new CA certificate and key...")
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
panic(err)
}
ca := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
Organization: []string{"gitmproxy"},
CommonName: "Gopher in the middle Root CA",
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour * 30), // 30 years
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
BasicConstraintsValid: true,
IsCA: true,
MaxPathLen: 2,
MaxPathLenZero: false,
}
der, err := x509.CreateCertificate(rand.Reader, ca, ca, &priv.PublicKey, priv)
if err != nil {
panic(err)
}
// Write cert
certOut, err := os.Create(certPath)
if err != nil {
panic(err)
}
defer certOut.Close()
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil {
panic(err)
}
// Write key
keyOut, err := os.Create(keyPath)
if err != nil {
panic(err)
}
defer keyOut.Close()
if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
panic(err)
}
log.Info("CA certificate and key generated.")
}