Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

80 rader
1.9 KiB

  1. from jose.backends.base import Key
  2. from jose.constants import ALGORITHMS
  3. from jose.exceptions import JWKError
  4. try:
  5. from jose.backends import RSAKey # noqa: F401
  6. except ImportError:
  7. pass
  8. try:
  9. from jose.backends import ECKey # noqa: F401
  10. except ImportError:
  11. pass
  12. try:
  13. from jose.backends import AESKey # noqa: F401
  14. except ImportError:
  15. pass
  16. try:
  17. from jose.backends import DIRKey # noqa: F401
  18. except ImportError:
  19. pass
  20. try:
  21. from jose.backends import HMACKey # noqa: F401
  22. except ImportError:
  23. pass
  24. def get_key(algorithm):
  25. if algorithm in ALGORITHMS.KEYS:
  26. return ALGORITHMS.KEYS[algorithm]
  27. elif algorithm in ALGORITHMS.HMAC: # noqa: F811
  28. return HMACKey
  29. elif algorithm in ALGORITHMS.RSA:
  30. from jose.backends import RSAKey # noqa: F811
  31. return RSAKey
  32. elif algorithm in ALGORITHMS.EC:
  33. from jose.backends import ECKey # noqa: F811
  34. return ECKey
  35. elif algorithm in ALGORITHMS.AES:
  36. from jose.backends import AESKey # noqa: F811
  37. return AESKey
  38. elif algorithm == ALGORITHMS.DIR:
  39. from jose.backends import DIRKey # noqa: F811
  40. return DIRKey
  41. return None
  42. def register_key(algorithm, key_class):
  43. if not issubclass(key_class, Key):
  44. raise TypeError("Key class is not a subclass of jwk.Key")
  45. ALGORITHMS.KEYS[algorithm] = key_class
  46. ALGORITHMS.SUPPORTED.add(algorithm)
  47. return True
  48. def construct(key_data, algorithm=None):
  49. """
  50. Construct a Key object for the given algorithm with the given
  51. key_data.
  52. """
  53. # Allow for pulling the algorithm off of the passed in jwk.
  54. if not algorithm and isinstance(key_data, dict):
  55. algorithm = key_data.get("alg", None)
  56. if not algorithm:
  57. raise JWKError("Unable to find an algorithm for key")
  58. key_class = get_key(algorithm)
  59. if not key_class:
  60. raise JWKError("Unable to find an algorithm for key")
  61. return key_class(key_data, algorithm)