This repository has been archived by the owner on Jan 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcerts.go
74 lines (63 loc) · 1.65 KB
/
certs.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
package logx
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
)
// Generates certificate an
func GenerateCerts(validFor time.Duration) (*x509.Certificate, *rsa.PrivateKey, error) {
key, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, err
}
now := time.Now()
template := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Monstercat Inc."},
},
NotBefore: now,
NotAfter: now.Add(validFor),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
return nil, nil, err
}
certificate, err := x509.ParseCertificate(derBytes)
if err != nil {
return nil, nil, err
}
return certificate, key, nil
}
func WriteCertificate(cert *x509.Certificate, outFile string) error {
certOut, err := os.Create(outFile)
defer certOut.Close()
if err != nil {
return err
}
return pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
}
func WritePrivateKey(key *rsa.PrivateKey, outFile string) error {
privBytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return err
}
keyOut, err := os.Create(outFile)
defer keyOut.Close()
if err != nil {
return err
}
return pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
}