forked from pivotal-cf/cred-alert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cert.go
62 lines (50 loc) · 1.29 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
package config
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
)
func LoadCertificate(certPath, keyPath, password string) (tls.Certificate, error) {
if password == "" {
return tls.LoadX509KeyPair(certPath, keyPath)
}
certBytes, err := ioutil.ReadFile(certPath)
if err != nil {
return tls.Certificate{}, err
}
encryptedKeyBytes, err := ioutil.ReadFile(keyPath)
if err != nil {
return tls.Certificate{}, err
}
block, _ := pem.Decode(encryptedKeyBytes)
if block == nil {
return tls.Certificate{}, errors.New("error decoding PEM in key file")
}
decryptedKeyBytes, err := x509.DecryptPEMBlock(block, []byte(password))
if err != nil {
return tls.Certificate{}, err
}
pemBlock := &pem.Block{
Type: "PRIVATE KEY", // go don't care
Bytes: decryptedKeyBytes,
}
keyBytes := pem.EncodeToMemory(pemBlock)
return tls.X509KeyPair(certBytes, keyBytes)
}
func LoadCertificatePool(certFiles ...string) (*x509.CertPool, error) {
certPool := x509.NewCertPool()
for _, certFileName := range certFiles {
bs, err := ioutil.ReadFile(certFileName)
if err != nil {
return certPool, err
}
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
return certPool, fmt.Errorf("failed to append client certs from pem: %s", err.Error())
}
}
return certPool, nil
}