Files
2026-02-17 23:30:49 +01:00

82 lines
1.8 KiB
Go

// 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"
)
func init() {
SigningMethod = new(SigningMethodEd25519)
jwt.RegisterSigningMethod(SigningMethod.Alg(), func() jwt.SigningMethod {
return SigningMethod
})
}
var SigningMethod jwt.SigningMethod
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)