-
Notifications
You must be signed in to change notification settings - Fork 2
/
files.go
63 lines (55 loc) · 1.09 KB
/
files.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
package main
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"os"
)
func isPem(in []byte) bool {
return bytes.HasPrefix(in, []byte("-----"))
}
func pemToDer(in []byte) []byte {
b, _ := pem.Decode(in)
return b.Bytes
}
func readDerOrPem(filePath string) ([]byte, error) {
b, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
if isPem(b) {
b = pemToDer(b)
}
return b, nil
}
func readCert(caCertPath string) (*x509.Certificate, error) {
certBytes, err := readDerOrPem(caCertPath)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, err
}
return cert, nil
}
func readKey(caKeyPath string) (*rsa.PrivateKey, error) {
keyBytes, err := readDerOrPem(caKeyPath)
if err != nil {
return nil, err
}
key, err := x509.ParsePKCS1PrivateKey(keyBytes)
if err != nil {
return nil, err
}
return key, nil
}
func writePem(path string, data []byte) error {
return ioutil.WriteFile(path, data, 0644)
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}