gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

ed25519.go (1944B)


      1 package jwt
      2 
      3 import (
      4 	"errors"
      5 
      6 	"crypto/ed25519"
      7 )
      8 
      9 var (
     10 	ErrEd25519Verification = errors.New("ed25519: verification error")
     11 )
     12 
     13 // Implements the EdDSA family
     14 // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification
     15 type SigningMethodEd25519 struct{}
     16 
     17 // Specific instance for EdDSA
     18 var (
     19 	SigningMethodEdDSA *SigningMethodEd25519
     20 )
     21 
     22 func init() {
     23 	SigningMethodEdDSA = &SigningMethodEd25519{}
     24 	RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod {
     25 		return SigningMethodEdDSA
     26 	})
     27 }
     28 
     29 func (m *SigningMethodEd25519) Alg() string {
     30 	return "EdDSA"
     31 }
     32 
     33 // Implements the Verify method from SigningMethod
     34 // For this verify method, key must be an ed25519.PublicKey
     35 func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error {
     36 	var err error
     37 	var ed25519Key ed25519.PublicKey
     38 	var ok bool
     39 
     40 	if ed25519Key, ok = key.(ed25519.PublicKey); !ok {
     41 		return ErrInvalidKeyType
     42 	}
     43 
     44 	if len(ed25519Key) != ed25519.PublicKeySize {
     45 		return ErrInvalidKey
     46 	}
     47 
     48 	// Decode the signature
     49 	var sig []byte
     50 	if sig, err = DecodeSegment(signature); err != nil {
     51 		return err
     52 	}
     53 
     54 	// Verify the signature
     55 	if !ed25519.Verify(ed25519Key, []byte(signingString), sig) {
     56 		return ErrEd25519Verification
     57 	}
     58 
     59 	return nil
     60 }
     61 
     62 // Implements the Sign method from SigningMethod
     63 // For this signing method, key must be an ed25519.PrivateKey
     64 func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) {
     65 	var ed25519Key ed25519.PrivateKey
     66 	var ok bool
     67 
     68 	if ed25519Key, ok = key.(ed25519.PrivateKey); !ok {
     69 		return "", ErrInvalidKeyType
     70 	}
     71 
     72 	// ed25519.Sign panics if private key not equal to ed25519.PrivateKeySize
     73 	// this allows to avoid recover usage
     74 	if len(ed25519Key) != ed25519.PrivateKeySize {
     75 		return "", ErrInvalidKey
     76 	}
     77 
     78 	// Sign the string and return the encoded result
     79 	sig := ed25519.Sign(ed25519Key, []byte(signingString))
     80 	return EncodeSegment(sig), nil
     81 }