/
cert.go
82 lines (73 loc) · 2.16 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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package httpserve
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
pseudoRandom "math/rand"
"os"
"time"
)
func CreateCertificateIfNotExist(certFile string, keyFile string, commonName string, bits int) {
if _, err := os.Stat(certFile); err == nil {
// certFile already exists
return
}
if _, err := os.Stat(keyFile); err == nil {
// keyFile already exists
return
}
fmt.Println("Generating RSA key and certificate.")
pseudoRandom.Seed(time.Now().UTC().UnixNano())
priv, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
fmt.Println("Generate key:", err)
}
notBefore := time.Now()
notAfter := time.Now().AddDate(10, 0, 0) // the certificate should expire in 10 years
template := x509.Certificate{
SerialNumber: big.NewInt(pseudoRandom.Int63()),
Subject: pkix.Name{
CommonName: commonName,
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
fmt.Println("create cert:", err)
}
certOut, err := os.Create(certFile)
if err != nil {
fmt.Println("save cert:", err)
}
err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
fmt.Println("save cert:", err)
}
err = certOut.Close()
if err != nil {
fmt.Println("save cert:", err)
}
keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Println("save key:", err)
}
err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
if err != nil {
fmt.Println("save key:", err)
}
err = keyOut.Close()
if err != nil {
fmt.Println("save key:", err)
}
}