-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen_cert.go
More file actions
86 lines (72 loc) · 2.55 KB
/
Copy pathgen_cert.go
File metadata and controls
86 lines (72 loc) · 2.55 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
81
82
83
84
85
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha1"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
)
func GenCert(sni string) {
// 1. Generate Root CA
caPriv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
pubBytes, _ := x509.MarshalPKIXPublicKey(&caPriv.PublicKey)
skid := sha1.Sum(pubBytes)
caTemplate := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"NaiveProxy Local CA"},
CommonName: "NaiveProxy Root CA",
},
NotBefore: time.Now().Add(-1 * time.Hour),
NotAfter: time.Now().AddDate(10, 0, 0),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
SubjectKeyId: skid[:],
}
caBytes, _ := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caPriv.PublicKey, caPriv)
savePEM("rootCA.crt", "CERTIFICATE", caBytes)
saveKey("rootCA.key", caPriv)
// 2. Generate Server Cert (sni)
servPriv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
servPubBytes, _ := x509.MarshalPKIXPublicKey(&servPriv.PublicKey)
servSkid := sha1.Sum(servPubBytes)
servTemplate := &x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{
Organization: []string{"NaiveProxy Server"},
CommonName: sni,
},
DNSNames: []string{sni, "*." + sni},
NotBefore: time.Now().Add(-1 * time.Hour),
NotAfter: time.Now().AddDate(1, 0, 0),
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
SubjectKeyId: servSkid[:],
AuthorityKeyId: skid[:],
}
servBytes, _ := x509.CreateCertificate(rand.Reader, servTemplate, caTemplate, &servPriv.PublicKey, caPriv)
// ВАЖНО: Сохраняем ПОЛНУЮ цепочку (Leaf + Root) в один файл
f, _ := os.Create(sni + ".crt")
pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: servBytes})
pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: caBytes})
f.Close()
saveKey(sni+".key", servPriv)
}
func savePEM(filename, typeStr string, bytes []byte) {
f, _ := os.Create(filename)
pem.Encode(f, &pem.Block{Type: typeStr, Bytes: bytes})
f.Close()
}
func saveKey(filename string, key *ecdsa.PrivateKey) {
f, _ := os.Create(filename)
b, _ := x509.MarshalECPrivateKey(key)
pem.Encode(f, &pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
f.Close()
}