py_ecdsa.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Note: This file is named py_ecdsa.py because import behavior in Python 2
  2. # would cause ecdsa.py to squash the ecdsa library that it depends upon.
  3. import hashlib
  4. import ecdsa
  5. from jwt.algorithms import Algorithm
  6. from jwt.compat import string_types, text_type
  7. class ECAlgorithm(Algorithm):
  8. """
  9. Performs signing and verification operations using
  10. ECDSA and the specified hash function
  11. This class requires the ecdsa package to be installed.
  12. This is based off of the implementation in PyJWT 0.3.2
  13. """
  14. SHA256 = hashlib.sha256
  15. SHA384 = hashlib.sha384
  16. SHA512 = hashlib.sha512
  17. def __init__(self, hash_alg):
  18. self.hash_alg = hash_alg
  19. def prepare_key(self, key):
  20. if isinstance(key, ecdsa.SigningKey) or \
  21. isinstance(key, ecdsa.VerifyingKey):
  22. return key
  23. if isinstance(key, string_types):
  24. if isinstance(key, text_type):
  25. key = key.encode('utf-8')
  26. # Attempt to load key. We don't know if it's
  27. # a Signing Key or a Verifying Key, so we try
  28. # the Verifying Key first.
  29. try:
  30. key = ecdsa.VerifyingKey.from_pem(key)
  31. except ecdsa.der.UnexpectedDER:
  32. key = ecdsa.SigningKey.from_pem(key)
  33. else:
  34. raise TypeError('Expecting a PEM-formatted key.')
  35. return key
  36. def sign(self, msg, key):
  37. return key.sign(msg, hashfunc=self.hash_alg,
  38. sigencode=ecdsa.util.sigencode_string)
  39. def verify(self, msg, key, sig):
  40. try:
  41. return key.verify(sig, msg, hashfunc=self.hash_alg,
  42. sigdecode=ecdsa.util.sigdecode_string)
  43. except AssertionError:
  44. return False