padding.py 2.2 KB

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