forked from projectatomic/atomic-enterprise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
75 lines (64 loc) · 1.38 KB
/
crypto.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
package util
import (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
)
func CertPoolFromFile(filename string) (*x509.CertPool, error) {
pool := x509.NewCertPool()
if len(filename) == 0 {
return pool, nil
}
pemBlock, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
certs, err := CertificatesFromPEM(pemBlock)
if err != nil {
return nil, fmt.Errorf("Error reading %s: %s", filename, err)
}
for _, cert := range certs {
pool.AddCert(cert)
}
return pool, nil
}
func CertificatesFromFile(file string) ([]*x509.Certificate, error) {
if len(file) == 0 {
return nil, nil
}
pemBlock, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
certs, err := CertificatesFromPEM(pemBlock)
if err != nil {
return nil, fmt.Errorf("Error reading %s: %s", file, err)
}
return certs, nil
}
func CertificatesFromPEM(pemCerts []byte) ([]*x509.Certificate, error) {
ok := false
certs := []*x509.Certificate{}
for len(pemCerts) > 0 {
var block *pem.Block
block, pemCerts = pem.Decode(pemCerts)
if block == nil {
break
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return certs, err
}
certs = append(certs, cert)
ok = true
}
if !ok {
return certs, errors.New("Could not read any certificates")
}
return certs, nil
}