forked from kubeedge/kubeedge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
certfile.go
62 lines (52 loc) · 1.5 KB
/
certfile.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
package certutil
import (
"crypto"
"crypto/x509"
"encoding/pem"
"github.com/pkg/errors"
certutil "k8s.io/client-go/util/cert"
"k8s.io/client-go/util/keyutil"
)
func WriteKeyAndCert(keyFile string, certFile string, key crypto.Signer, cert *x509.Certificate) error {
err := WriteKey(keyFile, key)
if err != nil {
return err
}
err = WriteCert(certFile, cert)
if err != nil {
return err
}
return nil
}
// WriteKey stores the given key at the given location
func WriteKey(pkiPath string, key crypto.Signer) error {
if key == nil {
return errors.New("private key cannot be nil when writing to file")
}
encoded, err := keyutil.MarshalPrivateKeyToPEM(key)
if err != nil {
return errors.Wrapf(err, "unable to marshal private key to PEM")
}
if err := keyutil.WriteKey(pkiPath, encoded); err != nil {
return errors.Wrapf(err, "unable to write private key to file %s", pkiPath)
}
return nil
}
// WriteCert stores the given certificate at the given location
func WriteCert(certPath string, cert *x509.Certificate) error {
if cert == nil {
return errors.New("certificate cannot be nil when writing to file")
}
if err := certutil.WriteCert(certPath, EncodeCertPEM(cert)); err != nil {
return errors.Wrapf(err, "unable to write certificate to file %s", certPath)
}
return nil
}
// EncodeCertPEM returns PEM-encoded certificate data
func EncodeCertPEM(cert *x509.Certificate) []byte {
block := pem.Block{
Type: certutil.CertificateBlockType,
Bytes: cert.Raw,
}
return pem.EncodeToMemory(&block)
}