VictoriaMetrics/vendor/github.com/golang-jwt/jwt/v5/ed25519.go

80 lines
2.0 KiB
Go
Raw Normal View History

2023-07-07 09:04:32 +02:00
package jwt
import (
"crypto"
"crypto/ed25519"
"crypto/rand"
2023-11-13 18:50:16 +01:00
"errors"
2023-07-07 09:04:32 +02:00
)
var (
ErrEd25519Verification = errors.New("ed25519: verification error")
)
// SigningMethodEd25519 implements the EdDSA family.
// Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification
type SigningMethodEd25519 struct{}
// Specific instance for EdDSA
var (
SigningMethodEdDSA *SigningMethodEd25519
)
func init() {
SigningMethodEdDSA = &SigningMethodEd25519{}
RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod {
return SigningMethodEdDSA
})
}
func (m *SigningMethodEd25519) Alg() string {
return "EdDSA"
}
// Verify implements token verification for the SigningMethod.
// For this verify method, key must be an ed25519.PublicKey
2023-08-11 16:16:25 +02:00
func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error {
2023-07-07 09:04:32 +02:00
var ed25519Key ed25519.PublicKey
var ok bool
if ed25519Key, ok = key.(ed25519.PublicKey); !ok {
2023-12-11 09:48:36 +01:00
return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType)
2023-07-07 09:04:32 +02:00
}
if len(ed25519Key) != ed25519.PublicKeySize {
return ErrInvalidKey
}
// Verify the signature
if !ed25519.Verify(ed25519Key, []byte(signingString), sig) {
return ErrEd25519Verification
}
return nil
}
// Sign implements token signing for the SigningMethod.
// For this signing method, key must be an ed25519.PrivateKey
2023-08-11 16:16:25 +02:00
func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) {
2023-07-07 09:04:32 +02:00
var ed25519Key crypto.Signer
var ok bool
if ed25519Key, ok = key.(crypto.Signer); !ok {
2023-12-11 09:48:36 +01:00
return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType)
2023-07-07 09:04:32 +02:00
}
if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok {
2023-08-11 16:16:25 +02:00
return nil, ErrInvalidKey
2023-07-07 09:04:32 +02:00
}
2023-08-11 16:16:25 +02:00
// Sign the string and return the result. ed25519 performs a two-pass hash
// as part of its algorithm. Therefore, we need to pass a non-prehashed
// message into the Sign function, as indicated by crypto.Hash(0)
2023-07-07 09:04:32 +02:00
sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0))
if err != nil {
2023-08-11 16:16:25 +02:00
return nil, err
2023-07-07 09:04:32 +02:00
}
2023-08-11 16:16:25 +02:00
return sig, nil
2023-07-07 09:04:32 +02:00
}