-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
64 lines (56 loc) · 1.73 KB
/
util.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
package authority
import (
"crypto/x509"
"strings"
"github.com/effective-security/xlog"
"github.com/effective-security/xpki/cryptoprov"
"github.com/effective-security/xpki/csr"
"github.com/effective-security/xpki/x/fileutil"
"github.com/pkg/errors"
"github.com/spf13/afero"
)
// GenCert creates certificate and stores key and certs to specified location
func (ca *Issuer) GenCert(crypto cryptoprov.Provider, req *csr.CertificateRequest, profile, certFile, keyFile string) (*x509.Certificate, []byte, error) {
logger.KV(xlog.INFO,
"profile", profile,
"cn", req.CommonName,
"cert", certFile,
)
c := csr.NewProvider(crypto)
csrPEM, key, _, _, err := c.CreateRequestAndExportKey(req)
if err != nil {
return nil, nil, errors.WithMessage(err, "process request")
}
crt, certPEM, err := ca.Sign(csr.SignRequest{
SAN: req.SAN,
Request: string(csrPEM),
Profile: profile,
Extensions: req.Extensions,
Subject: &csr.X509Subject{
CommonName: req.CommonName,
Names: req.Names,
SerialNumber: req.SerialNumber,
},
})
if err != nil {
return nil, nil, err
}
err = fileutil.Vfs.Rename(certFile, certFile+".bak")
if err != nil {
logger.KV(xlog.WARNING, "reason", "move", "file", certFile, "err", err.Error())
}
err = fileutil.Vfs.Rename(keyFile, keyFile+".bak")
if err != nil {
logger.KV(xlog.WARNING, "reason", "move", "file", keyFile, "err", err.Error())
}
certBundle := strings.TrimSpace(string(certPEM)) + "\n" + ca.PEM()
err = afero.WriteFile(fileutil.Vfs, certFile, []byte(certBundle), 0664)
if err != nil {
return nil, nil, errors.WithStack(err)
}
err = afero.WriteFile(fileutil.Vfs, keyFile, key, 0600)
if err != nil {
return nil, nil, errors.WithStack(err)
}
return crt, certPEM, nil
}