ed25519.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package jwt
  2. import (
  3. "errors"
  4. "crypto"
  5. "crypto/ed25519"
  6. "crypto/rand"
  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, signature string, key interface{}) error {
  30. var err error
  31. var ed25519Key ed25519.PublicKey
  32. var ok bool
  33. if ed25519Key, ok = key.(ed25519.PublicKey); !ok {
  34. return ErrInvalidKeyType
  35. }
  36. if len(ed25519Key) != ed25519.PublicKeySize {
  37. return ErrInvalidKey
  38. }
  39. // Decode the signature
  40. var sig []byte
  41. if sig, err = DecodeSegment(signature); err != nil {
  42. return err
  43. }
  44. // Verify the signature
  45. if !ed25519.Verify(ed25519Key, []byte(signingString), sig) {
  46. return ErrEd25519Verification
  47. }
  48. return nil
  49. }
  50. // Sign implements token signing for the SigningMethod.
  51. // For this signing method, key must be an ed25519.PrivateKey
  52. func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) {
  53. var ed25519Key crypto.Signer
  54. var ok bool
  55. if ed25519Key, ok = key.(crypto.Signer); !ok {
  56. return "", ErrInvalidKeyType
  57. }
  58. if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok {
  59. return "", ErrInvalidKey
  60. }
  61. // Sign the string and return the encoded result
  62. // 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)
  63. sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0))
  64. if err != nil {
  65. return "", err
  66. }
  67. return EncodeSegment(sig), nil
  68. }