padding.py 2.1 KB

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