/
local_file_system_kprovider.go
70 lines (57 loc) · 1.79 KB
/
local_file_system_kprovider.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
64
65
66
67
68
69
70
package kprovider
import (
"crypto/rsa"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/spf13/afero"
"io/ioutil"
"os/user"
"strings"
)
type LocalFileSystemKProvider struct {
FileSystem afero.Fs
}
func NewLocalFileSystemKProvider() KeyProvider {
return LocalFileSystemKProvider{
FileSystem: afero.NewOsFs(),
}
}
func (w LocalFileSystemKProvider) LoadPrivateKey(context string, keyPair string) (*rsa.PrivateKey, error) {
usr, err := user.Current()
if err != nil {
return nil, err
}
privateKeyFilePath := fmt.Sprintf("%s/.%s/%s", usr.HomeDir, context, keyPair)
file, err := w.FileSystem.Open(privateKeyFilePath)
if err != nil {
return nil, fmt.Errorf("unable to load private key from file %s: %s", privateKeyFilePath, err.Error())
}
defer file.Close()
keyData, err := ioutil.ReadAll(file)
if err != nil {
return nil, fmt.Errorf("unable to load private key from file %s: %s", privateKeyFilePath, err.Error())
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(keyData)
if err != nil {
return nil, fmt.Errorf("invalid PEM encoded private key on file %s: %s", privateKeyFilePath, err.Error())
}
return key, nil
}
func (w LocalFileSystemKProvider) LoadKeyUid(context string, keyPair string) (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
publicKeyFilePath := fmt.Sprintf("%s/.%s/%s.pub", usr.HomeDir, context, keyPair)
file, err := w.FileSystem.Open(publicKeyFilePath)
if err != nil {
return "", fmt.Errorf("unable to load public key from file %s: %s", publicKeyFilePath, err.Error())
}
defer file.Close()
keyData, err := ioutil.ReadAll(file)
if err != nil {
return "", fmt.Errorf("unable to load public key from file %s: %s", publicKeyFilePath, err.Error())
}
keyFields := strings.Fields(string(keyData))
return keyFields[len(keyFields)-1], nil
}