github.com/BTBurke/caddy-jwt@v3.7.1+incompatible/key_utils.go (about) 1 package jwt 2 3 import ( 4 "crypto/ecdsa" 5 "crypto/rsa" 6 "fmt" 7 "io/ioutil" 8 9 "github.com/dgrijalva/jwt-go" 10 ) 11 12 func ParsePublicKey(pem []byte) (interface{}, error) { 13 result, err := jwt.ParseRSAPublicKeyFromPEM(pem) 14 if err != nil { 15 result2, err2 := jwt.ParseECPublicKeyFromPEM(pem) 16 if err2 == nil { 17 return result2, nil 18 } 19 } 20 return result, err 21 } 22 23 func ReadPublicKeyFile(filepath string) (interface{}, error) { 24 content, err := ioutil.ReadFile(filepath) 25 if err != nil { 26 return nil, err 27 } 28 return ParsePublicKey(content) 29 } 30 31 func IsRsaPublicKey(key interface{}) bool { 32 _, ok := key.(*rsa.PublicKey) 33 return ok 34 } 35 36 func IsEcdsaPublicKey(key interface{}) bool { 37 _, ok := key.(*ecdsa.PublicKey) 38 return ok 39 } 40 41 func IsRsaToken(token *jwt.Token) bool { 42 _, ok := token.Method.(*jwt.SigningMethodRSA) 43 return ok 44 } 45 46 func IsEcdsaToken(token *jwt.Token) bool { 47 _, ok := token.Method.(*jwt.SigningMethodECDSA) 48 return ok 49 } 50 51 func IsHmacToken(token *jwt.Token) bool { 52 _, ok := token.Method.(*jwt.SigningMethodHMAC) 53 return ok 54 } 55 56 func AssertPublicKeyAndTokenCombination(publicKey interface{}, token *jwt.Token) error { 57 if IsRsaPublicKey(publicKey) && !IsRsaToken(token) { 58 return fmt.Errorf("expect token signed with RSA but got %v", token.Header["alg"]) 59 } 60 if IsEcdsaPublicKey(publicKey) && !IsEcdsaToken(token) { 61 return fmt.Errorf("expect token signed with ECDSA but got %v", token.Header["alg"]) 62 } 63 return nil 64 } 65 66 func AssertHmacToken(token *jwt.Token) error { 67 if !IsHmacToken(token) { 68 return fmt.Errorf("expect token signed with HMAC but got %v", token.Header["alg"]) 69 } 70 return nil 71 }