2023-09-29 07:41:01 +02:00
|
|
|
package jwtutil
|
|
|
|
|
|
|
|
import (
|
2023-10-03 19:24:03 +02:00
|
|
|
"strings"
|
|
|
|
|
2023-09-29 07:41:01 +02:00
|
|
|
"github.com/lestrrat-go/jwx/v2/jwa"
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwk"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2023-10-03 19:24:03 +02:00
|
|
|
func AddKeyWithSigningAlgo(keySet jwk.Set, key jwk.Key, signingAlgorithm jwa.SignatureAlgorithm) error {
|
|
|
|
addedKey := key
|
|
|
|
|
|
|
|
if !strings.HasPrefix(string(signingAlgorithm), "HS") {
|
|
|
|
publicKey, err := key.PublicKey()
|
|
|
|
if err != nil {
|
|
|
|
return errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
addedKey = publicKey
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := addedKey.Set(jwk.AlgorithmKey, signingAlgorithm); err != nil {
|
|
|
|
return errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := keySet.AddKey(addedKey); err != nil {
|
|
|
|
return errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-29 07:41:01 +02:00
|
|
|
func NewKeySet(keys ...jwk.Key) (jwk.Set, error) {
|
|
|
|
set := jwk.NewSet()
|
|
|
|
|
|
|
|
for _, k := range keys {
|
|
|
|
if err := set.AddKey(k); err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return set, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSymmetricKey(secret []byte) (jwk.Key, error) {
|
|
|
|
key, err := jwk.FromRaw(secret)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := key.Set(jwk.AlgorithmKey, jwa.HS256); err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSymmetricKeySet(secrets ...[]byte) (jwk.Set, error) {
|
|
|
|
keys := make([]jwk.Key, len(secrets))
|
|
|
|
|
|
|
|
for idx, sec := range secrets {
|
|
|
|
key, err := NewSymmetricKey(sec)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
keys[idx] = key
|
|
|
|
}
|
|
|
|
|
|
|
|
keySet, err := NewKeySet(keys...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return keySet, nil
|
|
|
|
}
|