You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ed25519.go 1.9KB

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