pycrypto.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import Crypto.Hash.SHA256
  2. import Crypto.Hash.SHA384
  3. import Crypto.Hash.SHA512
  4. from Crypto.PublicKey import RSA
  5. from Crypto.Signature import PKCS1_v1_5
  6. from jwt.algorithms import Algorithm
  7. from jwt.compat import string_types, text_type
  8. class RSAAlgorithm(Algorithm):
  9. """
  10. Performs signing and verification operations using
  11. RSASSA-PKCS-v1_5 and the specified hash function.
  12. This class requires PyCrypto package to be installed.
  13. This is based off of the implementation in PyJWT 0.3.2
  14. """
  15. SHA256 = Crypto.Hash.SHA256
  16. SHA384 = Crypto.Hash.SHA384
  17. SHA512 = Crypto.Hash.SHA512
  18. def __init__(self, hash_alg):
  19. self.hash_alg = hash_alg
  20. def prepare_key(self, key):
  21. if isinstance(key, RSA._RSAobj):
  22. return key
  23. if isinstance(key, string_types):
  24. if isinstance(key, text_type):
  25. key = key.encode('utf-8')
  26. key = RSA.importKey(key)
  27. else:
  28. raise TypeError('Expecting a PEM- or RSA-formatted key.')
  29. return key
  30. def sign(self, msg, key):
  31. return PKCS1_v1_5.new(key).sign(self.hash_alg.new(msg))
  32. def verify(self, msg, key, sig):
  33. return PKCS1_v1_5.new(key).verify(self.hash_alg.new(msg), sig)