-
Notifications
You must be signed in to change notification settings - Fork 2
/
cert.go
97 lines (76 loc) · 1.71 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package openssl
import (
"fmt"
"io/ioutil"
)
type Cert struct {
path string
key string
content []byte
contentKey []byte
}
func (o *Openssl) LoadOrCreateCert(filename, keyfile, cn string, ca *CA, server bool) (*Cert, error) {
cert, err := o.LoadCert(filename, keyfile)
if err != nil {
return o.CreateCert(filename, keyfile, cn, ca, server)
}
return cert, nil
}
func (o *Openssl) LoadCert(filename, keyfile string) (*Cert, error) {
var err error
o.Init()
filename = o.Path + "/" + filename
keyfile = o.Path + "/" + keyfile
c := &Cert{}
c.path = filename
c.key = keyfile
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) CreateCert(filename, keyfile, cn string, ca *CA, server bool) (*Cert, error) {
o.Init()
filename = o.Path + "/" + filename
keyfile = o.Path + "/" + keyfile
request, err := o.CreateCSR(cn, server)
if err != nil {
return nil, fmt.Errorf("Create csr failed: " + err.Error())
}
cert, err := ca.Sign(request)
if err != nil {
return nil, fmt.Errorf("Sign csr failed: ", err)
}
cert.path = filename
cert.key = keyfile
if err = ioutil.WriteFile(cert.path, cert.content, 0600); err != nil {
return nil, err
}
if err = ioutil.WriteFile(cert.key, request.contentKey, 0600); err != nil {
return nil, err
}
return cert, nil
}
func (c *Cert) GetFilePath() string {
return c.path
}
func (c *Cert) GetKeyPath() string {
return c.key
}
func (c *Cert) String() string {
if c != nil {
return string(c.content)
}
return ""
}
func (c *Cert) KeyString() string {
if c != nil {
return string(c.contentKey)
}
return ""
}