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 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package jwt
  2. import (
  3. "crypto"
  4. "crypto/ed25519"
  5. "crypto/rand"
  6. "errors"
  7. )
  8. var (
  9. ErrEd25519Verification = errors.New("ed25519: verification error")
  10. )
  11. // SigningMethodEd25519 implements the EdDSA family.
  12. // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification
  13. type SigningMethodEd25519 struct{}
  14. // Specific instance for EdDSA
  15. var (
  16. SigningMethodEdDSA *SigningMethodEd25519
  17. )
  18. func init() {
  19. SigningMethodEdDSA = &SigningMethodEd25519{}
  20. RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod {
  21. return SigningMethodEdDSA
  22. })
  23. }
  24. func (m *SigningMethodEd25519) Alg() string {
  25. return "EdDSA"
  26. }
  27. // Verify implements token verification for the SigningMethod.
  28. // For this verify method, key must be an ed25519.PublicKey
  29. func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error {
  30. var ed25519Key ed25519.PublicKey
  31. var ok bool
  32. if ed25519Key, ok = key.(ed25519.PublicKey); !ok {
  33. return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType)
  34. }
  35. if len(ed25519Key) != ed25519.PublicKeySize {
  36. return ErrInvalidKey
  37. }
  38. // Verify the signature
  39. if !ed25519.Verify(ed25519Key, []byte(signingString), sig) {
  40. return ErrEd25519Verification
  41. }
  42. return nil
  43. }
  44. // Sign implements token signing for the SigningMethod.
  45. // For this signing method, key must be an ed25519.PrivateKey
  46. func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) {
  47. var ed25519Key crypto.Signer
  48. var ok bool
  49. if ed25519Key, ok = key.(crypto.Signer); !ok {
  50. return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType)
  51. }
  52. if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok {
  53. return nil, ErrInvalidKey
  54. }
  55. // Sign the string and return the result. ed25519 performs a two-pass hash
  56. // as part of its algorithm. Therefore, we need to pass a non-prehashed
  57. // message into the Sign function, as indicated by crypto.Hash(0)
  58. sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0))
  59. if err != nil {
  60. return nil, err
  61. }
  62. return sig, nil
  63. }