-
Notifications
You must be signed in to change notification settings - Fork 246
/
x509util.go
61 lines (54 loc) · 1.22 KB
/
x509util.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
package x509util
import (
"crypto/x509"
"errors"
"io/fs"
"os"
)
// CustomCertPool creates a x509.CertPool from a filepath string.
//
// If the path is a directory, it walks the directory and adds all files to the
// pool.
func CustomCertPool(caPath string) (*x509.CertPool, error) {
fi, err := os.Stat(caPath)
if err != nil {
return nil, err
}
var caFiles [][]byte
if fi.IsDir() {
caFiles, err = dirContents(caPath)
if err != nil {
return nil, err
}
} else {
contents, err := os.ReadFile(caPath)
if err != nil {
return nil, err
}
caFiles = append(caFiles, contents)
}
certPool := x509.NewCertPool()
for _, caBytes := range caFiles {
if ok := certPool.AppendCertsFromPEM(caBytes); !ok {
return nil, errors.New("failed to append certs from CA PEM")
}
}
return certPool, nil
}
func dirContents(dirPath string) ([][]byte, error) {
var allContents [][]byte
dirFS := os.DirFS(dirPath)
if err := fs.WalkDir(dirFS, ".", func(path string, d fs.DirEntry, err error) error {
if !d.IsDir() {
contents, err := fs.ReadFile(dirFS, d.Name())
if err != nil {
return err
}
allContents = append(allContents, contents)
}
return nil
}); err != nil {
return nil, err
}
return allContents, nil
}