-
Notifications
You must be signed in to change notification settings - Fork 20
/
jwk.go
57 lines (48 loc) · 1.13 KB
/
jwk.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
package clerk
import (
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/go-jose/go-jose/v3"
)
type JSONWebKeySet struct {
APIResource
Keys []*JSONWebKey `json:"keys"`
}
type JSONWebKey struct {
APIResource
Key any `json:"key"`
KeyID string `json:"kid"`
Algorithm string `json:"alg"`
Use string `json:"use"`
raw jose.JSONWebKey
}
func (k *JSONWebKey) UnmarshalJSON(data []byte) error {
err := k.raw.UnmarshalJSON(data)
if err != nil {
return err
}
k.Key = k.raw.Key
k.KeyID = k.raw.KeyID
k.Algorithm = k.raw.Algorithm
k.Use = k.raw.Use
return nil
}
// JSONWebKeyFromPEM returns a JWK from an RSA key.
func JSONWebKeyFromPEM(key string) (*JSONWebKey, error) {
block, _ := pem.Decode([]byte(key))
if block == nil {
return nil, fmt.Errorf("invalid PEM-encoded block")
}
if block.Type != "PUBLIC KEY" {
return nil, fmt.Errorf("invalid key type, expected a public key")
}
rsaPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %w", err)
}
return &JSONWebKey{
Key: rsaPublicKey,
Algorithm: "RS256",
}, nil
}