-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gencert.go
75 lines (71 loc) · 1.87 KB
/
gencert.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
package main
import (
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"os"
"time"
"github.com/anacrolix/bargle"
)
// https://github.com/golang/go/issues/33310#issuecomment-537251383
var maxSerialNumber = new(big.Int).SetBytes([]byte{127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255})
func genCert() bargle.Command {
var params struct {
CommonName string `arg:"positional"`
DnsNames []string `arg:"positional" arity:"*"`
}
cmd := bargle.FromStruct(¶ms)
cmd.Desc = "sign a certificate"
cmd.DefaultAction = func() (err error) {
privKeyBytes, err := os.ReadFile("ca.key")
if err != nil {
return err
}
b, _ := pem.Decode(privKeyBytes)
privKey, err := x509.ParsePKCS1PrivateKey(b.Bytes)
if err != nil {
return fmt.Errorf("parsing private key: %w", err)
}
caCertBytes, err := os.ReadFile("ca.pem")
if err != nil {
return err
}
b, _ = pem.Decode(caCertBytes)
caCert, err := x509.ParseCertificate(b.Bytes)
if err != nil {
return fmt.Errorf("parsing ca cert: %w", err)
}
//caCert, err := tls.LoadX509KeyPair("ca.pem", "ca.key")
//if err != nil {
// return err
//}
serialNumber, err := rand.Int(rand.Reader, maxSerialNumber)
if err != nil {
return
}
cert, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{
Subject: pkix.Name{
Organization: []string{"btlink"},
OrganizationalUnit: []string{"root CA"},
CommonName: params.CommonName,
},
SerialNumber: serialNumber,
DNSNames: params.DnsNames,
// https://stackoverflow.com/a/65239775/149482
NotAfter: time.Now().AddDate(1, 0, 0),
NotBefore: time.Now(),
}, caCert, &privKey.PublicKey, privKey)
if err != nil {
return err
}
err = pem.Encode(os.Stdout, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
})
return
}
return cmd
}