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
|
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io"
"math/big"
mrand "math/rand"
"time"
)
const certPrefix = "UNLIMITED"
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz")
func randStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[mrand.Intn(len(letterRunes))]
}
return string(b)
}
type caInfo struct {
cacrt, cakey string
}
func newCaInfo(cacrt string, cakey string) caInfo {
return caInfo{cacrt, cakey}
}
// CertWriter main handler
func (ci *caInfo) CertWriter(out io.Writer) {
catls, err := tls.LoadX509KeyPair(ci.cacrt, ci.cakey)
if err != nil {
panic(err)
}
ca, err := x509.ParseCertificate(catls.Certificate[0])
if err != nil {
panic(err)
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
subjectKeyID := make([]byte, 20)
rand.Read(subjectKeyID)
_ = randStringRunes(25)
// Prepare certificate
cert := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
//CommonName: certPrefix + randStringRunes(25),
CommonName: certPrefix,
},
NotBefore: time.Now().AddDate(0, 0, -7),
NotAfter: time.Now().AddDate(0, 0, expiryDays),
SubjectKeyId: subjectKeyID,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
KeyUsage: x509.KeyUsageDigitalSignature,
}
priv, _ := rsa.GenerateKey(rand.Reader, keySize)
pub := &priv.PublicKey
// Sign the certificate
certB, err := x509.CreateCertificate(rand.Reader, cert, ca, pub, catls.PrivateKey)
// Write the private Key
pem.Encode(out, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
// Write the public key
pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: certB})
}
|