forked from BTBurke/caddy-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
key_utils.go
71 lines (60 loc) · 1.56 KB
/
key_utils.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
package jwt
import (
"crypto/ecdsa"
"crypto/rsa"
"fmt"
"io/ioutil"
"github.com/dgrijalva/jwt-go"
)
func ParsePublicKey(pem []byte) (interface{}, error) {
result, err := jwt.ParseRSAPublicKeyFromPEM(pem)
if err != nil {
result2, err2 := jwt.ParseECPublicKeyFromPEM(pem)
if err2 == nil {
return result2, nil
}
}
return result, err
}
func ReadPublicKeyFile(filepath string) (interface{}, error) {
content, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, err
}
return ParsePublicKey(content)
}
func IsRsaPublicKey(key interface{}) bool {
_, ok := key.(*rsa.PublicKey)
return ok
}
func IsEcdsaPublicKey(key interface{}) bool {
_, ok := key.(*ecdsa.PublicKey)
return ok
}
func IsRsaToken(token *jwt.Token) bool {
_, ok := token.Method.(*jwt.SigningMethodRSA)
return ok
}
func IsEcdsaToken(token *jwt.Token) bool {
_, ok := token.Method.(*jwt.SigningMethodECDSA)
return ok
}
func IsHmacToken(token *jwt.Token) bool {
_, ok := token.Method.(*jwt.SigningMethodHMAC)
return ok
}
func AssertPublicKeyAndTokenCombination(publicKey interface{}, token *jwt.Token) error {
if IsRsaPublicKey(publicKey) && !IsRsaToken(token) {
return fmt.Errorf("expect token signed with RSA but got %v", token.Header["alg"])
}
if IsEcdsaPublicKey(publicKey) && !IsEcdsaToken(token) {
return fmt.Errorf("expect token signed with ECDSA but got %v", token.Header["alg"])
}
return nil
}
func AssertHmacToken(token *jwt.Token) error {
if !IsHmacToken(token) {
return fmt.Errorf("expect token signed with HMAC but got %v", token.Header["alg"])
}
return nil
}