forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pem.go
50 lines (45 loc) · 1003 Bytes
/
pem.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
package pem
import (
"bytes"
"encoding/pem"
"io/ioutil"
"os"
"path/filepath"
)
func BlockFromFile(path string, blockType string) (*pem.Block, bool, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, false, err
}
block, ok := BlockFromBytes(data, blockType)
return block, ok, nil
}
func BlockFromBytes(data []byte, blockType string) (*pem.Block, bool) {
for {
block, remaining := pem.Decode(data)
if block == nil {
return nil, false
}
if block.Type == blockType {
return block, true
}
data = remaining
}
}
func BlockToFile(path string, block *pem.Block, mode os.FileMode) error {
b, err := BlockToBytes(block)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
return err
}
return ioutil.WriteFile(path, b, mode)
}
func BlockToBytes(block *pem.Block) ([]byte, error) {
b := bytes.Buffer{}
if err := pem.Encode(&b, block); err != nil {
return nil, err
}
return b.Bytes(), nil
}