padding.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import typing
  5. from cryptography.hazmat.primitives import hashes
  6. from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding
  7. from cryptography.hazmat.primitives.asymmetric import rsa
  8. class PKCS1v15(AsymmetricPadding):
  9. name = "EMSA-PKCS1-v1_5"
  10. class PSS(AsymmetricPadding):
  11. MAX_LENGTH = object()
  12. name = "EMSA-PSS"
  13. def __init__(self, mgf, salt_length):
  14. self._mgf = mgf
  15. if (
  16. not isinstance(salt_length, int)
  17. and salt_length is not self.MAX_LENGTH
  18. ):
  19. raise TypeError("salt_length must be an integer.")
  20. if salt_length is not self.MAX_LENGTH and salt_length < 0:
  21. raise ValueError("salt_length must be zero or greater.")
  22. self._salt_length = salt_length
  23. class OAEP(AsymmetricPadding):
  24. name = "EME-OAEP"
  25. def __init__(
  26. self,
  27. mgf: "MGF1",
  28. algorithm: hashes.HashAlgorithm,
  29. label: typing.Optional[bytes],
  30. ):
  31. if not isinstance(algorithm, hashes.HashAlgorithm):
  32. raise TypeError("Expected instance of hashes.HashAlgorithm.")
  33. self._mgf = mgf
  34. self._algorithm = algorithm
  35. self._label = label
  36. class MGF1(object):
  37. MAX_LENGTH = object()
  38. def __init__(self, algorithm: hashes.HashAlgorithm):
  39. if not isinstance(algorithm, hashes.HashAlgorithm):
  40. raise TypeError("Expected instance of hashes.HashAlgorithm.")
  41. self._algorithm = algorithm
  42. def calculate_max_pss_salt_length(
  43. key: typing.Union["rsa.RSAPrivateKey", "rsa.RSAPublicKey"],
  44. hash_algorithm: hashes.HashAlgorithm,
  45. ) -> int:
  46. if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
  47. raise TypeError("key must be an RSA public or private key")
  48. # bit length - 1 per RFC 3447
  49. emlen = (key.key_size + 6) // 8
  50. salt_length = emlen - hash_algorithm.digest_size - 2
  51. assert salt_length >= 0
  52. return salt_length