-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.go
116 lines (93 loc) · 2.08 KB
/
rsa.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package keyutil
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"io/ioutil"
"net/http"
"strings"
)
type rsaKeyType int
const (
rsaKeyInvalid rsaKeyType = iota
rsaKeyFile
rsaKeyURL
)
func LoadRsaKeys(keys []string) ([]*rsa.PublicKey, error) {
res := []*rsa.PublicKey{}
for _, key := range keys {
rsaKey, err := LoadRsaPublicKey(key)
if err != nil {
return res, err
}
res = append(res, rsaKey)
}
return res, nil
}
func LoadRsaPublicKey(key string) (*rsa.PublicKey, error) {
keyType := ParseKeyType(key)
switch keyType {
case rsaKeyURL:
return FetchRsaKey(key)
case rsaKeyFile:
return LoadRsaKeyFile(key)
}
return nil, errors.New("failed to load specified key")
}
// parseKeyType determines if the provided path for the key is a file or a url
func ParseKeyType(key string) rsaKeyType {
if strings.HasPrefix(key, "http://") || strings.HasPrefix(key, "https://") {
return rsaKeyURL
}
return rsaKeyFile
}
func LoadRsaKeyFile(path string) (*rsa.PublicKey, error) {
key, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return ParsePEM(key)
}
func LoadRsaPrivateKeyFile(path string) (*rsa.PrivateKey, error) {
key, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return ParsePrivateKey(key)
}
func FetchRsaKey(url string) (*rsa.PublicKey, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return ParsePEM(body)
}
func ParsePEM(c []byte) (*rsa.PublicKey, error) {
block, _ := pem.Decode(c)
cert, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
rsaPublicKey, ok := cert.(*rsa.PublicKey)
if !ok {
return nil, errors.New("invalid public key")
}
return rsaPublicKey, nil
}
func ParsePrivateKey(c []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(c)
cert, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
rsaPrivateKey, ok := cert.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("invalid public key")
}
return rsaPrivateKey, nil
}