-
Notifications
You must be signed in to change notification settings - Fork 0
/
google_public_key.go
68 lines (58 loc) · 1.61 KB
/
google_public_key.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
package secure_backend
import (
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
)
type googlePublicKey struct {
kid string
publicKey *rsa.PublicKey
}
func getGooglePublicKeys(url string) ([]*googlePublicKey, error) {
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("Google public key download failed / %v: %w", url, err)
} else if resp.Body != nil {
defer func() {
_ = resp.Body.Close()
}()
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Google public key download status error: %v / %v", resp.StatusCode, url)
}
metadataBody, err := io.ReadAll(resp.Body)
keys := map[string]string{}
err = json.Unmarshal(metadataBody, &keys)
if err != nil {
return nil, fmt.Errorf("Google public key parse failed: %w", err)
}
resultKeys := make([]*googlePublicKey, 0)
for kid, pemString := range keys {
key, err := parseGooglePublicKey(kid, pemString)
if err != nil {
return nil, fmt.Errorf("Google public key(%v) decode failed: %w", kid, err)
}
resultKeys = append(resultKeys, key)
}
return resultKeys, nil
}
func parseGooglePublicKey(kid string, key string) (*googlePublicKey, error) {
block, _ := pem.Decode([]byte(key))
if block == nil {
return nil, errors.New(fmt.Sprintf("PEM decode failed(%v)", kid))
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("ParseCertificate failed(%v): %w", kid, err)
}
pk, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return nil, errors.New(fmt.Sprintf("is not public key(%v)", kid))
}
return &googlePublicKey{kid, pk}, nil
}