-
Notifications
You must be signed in to change notification settings - Fork 2
/
csr.go
120 lines (95 loc) · 2.28 KB
/
csr.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package openssl
import (
"fmt"
"io/ioutil"
"os/exec"
"regexp"
log "github.com/cihub/seelog"
)
type CSR struct {
//path string
//key string
content []byte
contentKey []byte
}
func (o *Openssl) LoadCSR(filename, keyfile string) (*CSR, error) {
var err error
o.Init()
filename = o.Path + "/" + filename
keyfile = o.Path + "/" + keyfile
c := &CSR{}
c.content, err = ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
c.contentKey, err = ioutil.ReadFile(keyfile)
if err != nil {
return nil, err
}
return c, nil
}
func (o *Openssl) CreateCSR(cn string, server bool) (*CSR, error) {
var err error
o.Init()
log.Info("Create CSR")
c := &CSR{}
args := []string{
"req",
"-days", "3650",
"-nodes",
"-new",
"-keyout", "/dev/stdout",
"-out", "/dev/stdout",
"-config", o.GetConfigFile(),
"-batch",
"-utf8",
"-subj", "/C=" + o.Country + "/ST=" + o.Province + "/L=" + o.City + "/O=" + o.Organization + "/CN=" + cn + "/emailAddress=" + o.Email,
}
if server {
args = append(args, "-extensions", "server")
}
content, err := exec.Command("openssl", args...).CombinedOutput()
if err != nil {
return nil, fmt.Errorf("openssl req: " + err.Error() + " (" + string(content) + ")")
}
reCert := regexp.MustCompile("(?ms)-----BEGIN CERTIFICATE REQUEST-----(.+)-----END CERTIFICATE REQUEST-----")
reKey := regexp.MustCompile("(?ms)-----BEGIN PRIVATE KEY-----(.+)-----END PRIVATE KEY-----")
c.content = reCert.Find(content)
c.contentKey = reKey.Find(content)
if len(c.content) == 0 {
err = fmt.Errorf("Generated csr is 0 long")
return nil, err
}
if len(c.contentKey) == 0 {
err = fmt.Errorf("Generated csr key is 0 long")
return nil, err
}
//if err = ioutil.WriteFile(c.key, c.contentKey, 0600); err != nil {
//return nil, err
//}
return c, nil
}
func (csr *CSR) Save(filename string) error {
if err := ioutil.WriteFile(filename, csr.content, 0600); err != nil {
return err
}
return nil
}
func (csr *CSR) SaveKey(filename string) error {
if err := ioutil.WriteFile(filename, csr.contentKey, 0600); err != nil {
return err
}
return nil
}
func (csr *CSR) String() string {
if csr != nil {
return string(csr.content)
}
return ""
}
func (csr *CSR) KeyString() string {
if csr != nil {
return string(csr.contentKey)
}
return ""
}