-
Notifications
You must be signed in to change notification settings - Fork 546
/
ca.go
77 lines (64 loc) · 1.85 KB
/
ca.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
package main
// http://golang.org/src/pkg/crypto/tls/generate_cert.go
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"log"
"math/big"
"os"
"strings"
"time"
)
type CA struct {
orgName string
rsaBits int
}
func NewCA(orgName string, rsaBits int) *CA {
return &CA{orgName, rsaBits}
}
func (c *CA) Issue(isCA bool, host string, vaildFor time.Duration) {
priv, err := rsa.GenerateKey(rand.Reader, c.rsaBits)
if err != nil {
log.Fatalf("failed to generate private key: %s", err)
}
notBefore := time.Now().Add(-time.Duration(time.Hour))
notAfter := time.Now().Add(vaildFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Fatalf("failed to generate serial number: %s", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{c.orgName},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(host, ",")
for _, h := range hosts {
template.DNSNames = append(template.DNSNames, h)
}
if isCA {
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
}
outFile, err := os.Create("cert.crt")
defer outFile.Close()
if err != nil {
log.Fatalf("failed to open cert.crt for writing: %s", err)
}
pem.Encode(outFile, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
pem.Encode(outFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
}