padding.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 abc
  5. import typing
  6. from cryptography.hazmat.primitives import hashes
  7. from cryptography.hazmat.primitives._asymmetric import (
  8. AsymmetricPadding as AsymmetricPadding,
  9. )
  10. from cryptography.hazmat.primitives.asymmetric import rsa
  11. class PKCS1v15(AsymmetricPadding):
  12. name = "EMSA-PKCS1-v1_5"
  13. class _MaxLength:
  14. "Sentinel value for `MAX_LENGTH`."
  15. class _Auto:
  16. "Sentinel value for `AUTO`."
  17. class _DigestLength:
  18. "Sentinel value for `DIGEST_LENGTH`."
  19. class PSS(AsymmetricPadding):
  20. MAX_LENGTH = _MaxLength()
  21. AUTO = _Auto()
  22. DIGEST_LENGTH = _DigestLength()
  23. name = "EMSA-PSS"
  24. _salt_length: typing.Union[int, _MaxLength, _Auto, _DigestLength]
  25. def __init__(
  26. self,
  27. mgf: "MGF",
  28. salt_length: typing.Union[int, _MaxLength, _Auto, _DigestLength],
  29. ) -> None:
  30. self._mgf = mgf
  31. if not isinstance(
  32. salt_length, (int, _MaxLength, _Auto, _DigestLength)
  33. ):
  34. raise TypeError(
  35. "salt_length must be an integer, MAX_LENGTH, "
  36. "DIGEST_LENGTH, or AUTO"
  37. )
  38. if isinstance(salt_length, int) and salt_length < 0:
  39. raise ValueError("salt_length must be zero or greater.")
  40. self._salt_length = salt_length
  41. class OAEP(AsymmetricPadding):
  42. name = "EME-OAEP"
  43. def __init__(
  44. self,
  45. mgf: "MGF",
  46. algorithm: hashes.HashAlgorithm,
  47. label: typing.Optional[bytes],
  48. ):
  49. if not isinstance(algorithm, hashes.HashAlgorithm):
  50. raise TypeError("Expected instance of hashes.HashAlgorithm.")
  51. self._mgf = mgf
  52. self._algorithm = algorithm
  53. self._label = label
  54. class MGF(metaclass=abc.ABCMeta):
  55. _algorithm: hashes.HashAlgorithm
  56. class MGF1(MGF):
  57. MAX_LENGTH = _MaxLength()
  58. def __init__(self, algorithm: hashes.HashAlgorithm):
  59. if not isinstance(algorithm, hashes.HashAlgorithm):
  60. raise TypeError("Expected instance of hashes.HashAlgorithm.")
  61. self._algorithm = algorithm
  62. def calculate_max_pss_salt_length(
  63. key: typing.Union["rsa.RSAPrivateKey", "rsa.RSAPublicKey"],
  64. hash_algorithm: hashes.HashAlgorithm,
  65. ) -> int:
  66. if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
  67. raise TypeError("key must be an RSA public or private key")
  68. # bit length - 1 per RFC 3447
  69. emlen = (key.key_size + 6) // 8
  70. salt_length = emlen - hash_algorithm.digest_size - 2
  71. assert salt_length >= 0
  72. return salt_length