-
Notifications
You must be signed in to change notification settings - Fork 35
/
io.go
52 lines (43 loc) · 1.08 KB
/
io.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
package utils
import (
"encoding/pem"
"io/ioutil"
"os"
"github.com/centrifuge/go-centrifuge/errors"
)
// WriteKeyToPemFile writes encode of key and purpose to the file
func WriteKeyToPemFile(fileName string, keyPurpose string, key []byte) (err error) {
f, err := os.Create(fileName)
if err != nil {
return err
}
defer func() {
if err != nil {
return
}
err = f.Close()
}()
block := &pem.Block{
Type: keyPurpose,
Bytes: key,
}
if err := pem.Encode(f, block); err != nil {
return err
}
return f.Chmod(os.FileMode(0600))
}
// ReadKeyFromPemFile reads the pem file and returns the key with matching key purpose
func ReadKeyFromPemFile(fileName, keyPurpose string) (key []byte, err error) {
pemData, err := ioutil.ReadFile(fileName)
if err != nil {
return []byte{}, err
}
block, _ := pem.Decode(pemData)
if block == nil {
return []byte{}, errors.New("file [%s] is not a valid pem file", fileName)
}
if block.Type != keyPurpose {
return []byte{}, errors.New("key type mismatch got [%s] but expected [%s]", block.Type, keyPurpose)
}
return block.Bytes, nil
}