...
1
16
17 package cert
18
19 import (
20 "crypto/x509"
21 "fmt"
22 "os"
23 "path/filepath"
24 )
25
26
27
28 func CanReadCertAndKey(certPath, keyPath string) (bool, error) {
29 certReadable := canReadFile(certPath)
30 keyReadable := canReadFile(keyPath)
31
32 if certReadable == false && keyReadable == false {
33 return false, nil
34 }
35
36 if certReadable == false {
37 return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", certPath)
38 }
39
40 if keyReadable == false {
41 return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", keyPath)
42 }
43
44 return true, nil
45 }
46
47
48
49 func canReadFile(path string) bool {
50 f, err := os.Open(path)
51 if err != nil {
52 return false
53 }
54
55 defer f.Close()
56
57 return true
58 }
59
60
61
62
63
64 func WriteCert(certPath string, data []byte) error {
65 if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
66 return err
67 }
68 return os.WriteFile(certPath, data, os.FileMode(0644))
69 }
70
71
72
73 func NewPool(filename string) (*x509.CertPool, error) {
74 pemBlock, err := os.ReadFile(filename)
75 if err != nil {
76 return nil, err
77 }
78
79 pool, err := NewPoolFromBytes(pemBlock)
80 if err != nil {
81 return nil, fmt.Errorf("error creating pool from %s: %s", filename, err)
82 }
83 return pool, nil
84 }
85
86
87
88 func NewPoolFromBytes(pemBlock []byte) (*x509.CertPool, error) {
89 certs, err := ParseCertsPEM(pemBlock)
90 if err != nil {
91 return nil, err
92 }
93 pool := x509.NewCertPool()
94 for _, cert := range certs {
95 pool.AddCert(cert)
96 }
97 return pool, nil
98 }
99
100
101
102 func CertsFromFile(file string) ([]*x509.Certificate, error) {
103 pemBlock, err := os.ReadFile(file)
104 if err != nil {
105 return nil, err
106 }
107 certs, err := ParseCertsPEM(pemBlock)
108 if err != nil {
109 return nil, fmt.Errorf("error reading %s: %s", file, err)
110 }
111 return certs, nil
112 }
113
View as plain text