Added jwt signer
This commit is contained in:
78
protocol/meshcore/crypto/jwt/jwt.go
Normal file
78
protocol/meshcore/crypto/jwt/jwt.go
Normal file
@@ -0,0 +1,78 @@
|
||||
// Package jwt implements JSON Web Tokens (JWT) using Meshcore Ed25519 keys
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.maze.io/go/ham/protocol/meshcore/crypto"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var SigningMethod jwt.SigningMethod
|
||||
|
||||
func init() {
|
||||
SigningMethod = new(SigningMethodEd25519)
|
||||
}
|
||||
|
||||
type SigningMethodEd25519 struct{}
|
||||
|
||||
func (m *SigningMethodEd25519) Alg() string {
|
||||
return "Ed25519"
|
||||
}
|
||||
|
||||
func (m *SigningMethodEd25519) Sign(signingString string, key any) ([]byte, error) {
|
||||
var (
|
||||
privateKey *crypto.PrivateKey
|
||||
err error
|
||||
)
|
||||
switch key := key.(type) {
|
||||
case *crypto.PrivateKey:
|
||||
privateKey = key
|
||||
case []byte:
|
||||
switch len(key) {
|
||||
case crypto.SeedSize:
|
||||
if privateKey, err = crypto.NewPrivateKeyFromSeed(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
if privateKey, err = crypto.NewPrivateKey(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("jwt: invalid Ed25519 private key %T", key)
|
||||
}
|
||||
|
||||
return crypto.Sign(privateKey, []byte(signingString)), nil
|
||||
}
|
||||
|
||||
func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key any) error {
|
||||
var (
|
||||
publicKey *crypto.PublicKey
|
||||
err error
|
||||
)
|
||||
switch key := key.(type) {
|
||||
case *crypto.PublicKey:
|
||||
publicKey = key
|
||||
case crypto.PublicKey:
|
||||
publicKey = &key
|
||||
case *crypto.PrivateKey:
|
||||
if publicKey, err = crypto.NewPublicKey(key.PublicKey()); err != nil {
|
||||
return err
|
||||
}
|
||||
case []byte:
|
||||
if publicKey, err = crypto.NewPublicKey(key); err != nil {
|
||||
return err
|
||||
}
|
||||
case string:
|
||||
if publicKey, err = crypto.DecodePublicKey(key); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("jwt: invalid Ed25519 public key %T", key)
|
||||
}
|
||||
return crypto.Verify(publicKey, []byte(signingString), sig)
|
||||
}
|
||||
|
||||
var _ jwt.SigningMethod = (*SigningMethodEd25519)(nil)
|
||||
Reference in New Issue
Block a user