modes.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 import utils
  7. from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
  8. from cryptography.hazmat.primitives._cipheralgorithm import (
  9. BlockCipherAlgorithm,
  10. CipherAlgorithm,
  11. )
  12. class Mode(metaclass=abc.ABCMeta):
  13. @abc.abstractproperty
  14. def name(self) -> str:
  15. """
  16. A string naming this mode (e.g. "ECB", "CBC").
  17. """
  18. @abc.abstractmethod
  19. def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
  20. """
  21. Checks that all the necessary invariants of this (mode, algorithm)
  22. combination are met.
  23. """
  24. class ModeWithInitializationVector(metaclass=abc.ABCMeta):
  25. @abc.abstractproperty
  26. def initialization_vector(self) -> bytes:
  27. """
  28. The value of the initialization vector for this mode as bytes.
  29. """
  30. class ModeWithTweak(metaclass=abc.ABCMeta):
  31. @abc.abstractproperty
  32. def tweak(self) -> bytes:
  33. """
  34. The value of the tweak for this mode as bytes.
  35. """
  36. class ModeWithNonce(metaclass=abc.ABCMeta):
  37. @abc.abstractproperty
  38. def nonce(self) -> bytes:
  39. """
  40. The value of the nonce for this mode as bytes.
  41. """
  42. class ModeWithAuthenticationTag(metaclass=abc.ABCMeta):
  43. @abc.abstractproperty
  44. def tag(self) -> typing.Optional[bytes]:
  45. """
  46. The value of the tag supplied to the constructor of this mode.
  47. """
  48. def _check_aes_key_length(self, algorithm):
  49. if algorithm.key_size > 256 and algorithm.name == "AES":
  50. raise ValueError(
  51. "Only 128, 192, and 256 bit keys are allowed for this AES mode"
  52. )
  53. def _check_iv_length(self, algorithm):
  54. if len(self.initialization_vector) * 8 != algorithm.block_size:
  55. raise ValueError(
  56. "Invalid IV size ({}) for {}.".format(
  57. len(self.initialization_vector), self.name
  58. )
  59. )
  60. def _check_nonce_length(nonce: bytes, name: str, algorithm) -> None:
  61. if len(nonce) * 8 != algorithm.block_size:
  62. raise ValueError(
  63. "Invalid nonce size ({}) for {}.".format(len(nonce), name)
  64. )
  65. def _check_iv_and_key_length(self, algorithm):
  66. _check_aes_key_length(self, algorithm)
  67. _check_iv_length(self, algorithm)
  68. class CBC(Mode, ModeWithInitializationVector):
  69. name = "CBC"
  70. def __init__(self, initialization_vector: bytes):
  71. utils._check_byteslike("initialization_vector", initialization_vector)
  72. self._initialization_vector = initialization_vector
  73. @property
  74. def initialization_vector(self) -> bytes:
  75. return self._initialization_vector
  76. validate_for_algorithm = _check_iv_and_key_length
  77. class XTS(Mode, ModeWithTweak):
  78. name = "XTS"
  79. def __init__(self, tweak: bytes):
  80. utils._check_byteslike("tweak", tweak)
  81. if len(tweak) != 16:
  82. raise ValueError("tweak must be 128-bits (16 bytes)")
  83. self._tweak = tweak
  84. @property
  85. def tweak(self) -> bytes:
  86. return self._tweak
  87. def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
  88. if algorithm.key_size not in (256, 512):
  89. raise ValueError(
  90. "The XTS specification requires a 256-bit key for AES-128-XTS"
  91. " and 512-bit key for AES-256-XTS"
  92. )
  93. class ECB(Mode):
  94. name = "ECB"
  95. validate_for_algorithm = _check_aes_key_length
  96. class OFB(Mode, ModeWithInitializationVector):
  97. name = "OFB"
  98. def __init__(self, initialization_vector: bytes):
  99. utils._check_byteslike("initialization_vector", initialization_vector)
  100. self._initialization_vector = initialization_vector
  101. @property
  102. def initialization_vector(self) -> bytes:
  103. return self._initialization_vector
  104. validate_for_algorithm = _check_iv_and_key_length
  105. class CFB(Mode, ModeWithInitializationVector):
  106. name = "CFB"
  107. def __init__(self, initialization_vector: bytes):
  108. utils._check_byteslike("initialization_vector", initialization_vector)
  109. self._initialization_vector = initialization_vector
  110. @property
  111. def initialization_vector(self) -> bytes:
  112. return self._initialization_vector
  113. validate_for_algorithm = _check_iv_and_key_length
  114. class CFB8(Mode, ModeWithInitializationVector):
  115. name = "CFB8"
  116. def __init__(self, initialization_vector: bytes):
  117. utils._check_byteslike("initialization_vector", initialization_vector)
  118. self._initialization_vector = initialization_vector
  119. @property
  120. def initialization_vector(self) -> bytes:
  121. return self._initialization_vector
  122. validate_for_algorithm = _check_iv_and_key_length
  123. class CTR(Mode, ModeWithNonce):
  124. name = "CTR"
  125. def __init__(self, nonce: bytes):
  126. utils._check_byteslike("nonce", nonce)
  127. self._nonce = nonce
  128. @property
  129. def nonce(self) -> bytes:
  130. return self._nonce
  131. def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
  132. _check_aes_key_length(self, algorithm)
  133. _check_nonce_length(self.nonce, self.name, algorithm)
  134. class GCM(Mode, ModeWithInitializationVector, ModeWithAuthenticationTag):
  135. name = "GCM"
  136. _MAX_ENCRYPTED_BYTES = (2 ** 39 - 256) // 8
  137. _MAX_AAD_BYTES = (2 ** 64) // 8
  138. def __init__(
  139. self,
  140. initialization_vector: bytes,
  141. tag: typing.Optional[bytes] = None,
  142. min_tag_length: int = 16,
  143. ):
  144. # OpenSSL 3.0.0 constrains GCM IVs to [64, 1024] bits inclusive
  145. # This is a sane limit anyway so we'll enforce it here.
  146. utils._check_byteslike("initialization_vector", initialization_vector)
  147. if len(initialization_vector) < 8 or len(initialization_vector) > 128:
  148. raise ValueError(
  149. "initialization_vector must be between 8 and 128 bytes (64 "
  150. "and 1024 bits)."
  151. )
  152. self._initialization_vector = initialization_vector
  153. if tag is not None:
  154. utils._check_bytes("tag", tag)
  155. if min_tag_length < 4:
  156. raise ValueError("min_tag_length must be >= 4")
  157. if len(tag) < min_tag_length:
  158. raise ValueError(
  159. "Authentication tag must be {} bytes or longer.".format(
  160. min_tag_length
  161. )
  162. )
  163. self._tag = tag
  164. self._min_tag_length = min_tag_length
  165. @property
  166. def tag(self) -> typing.Optional[bytes]:
  167. return self._tag
  168. @property
  169. def initialization_vector(self) -> bytes:
  170. return self._initialization_vector
  171. def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
  172. _check_aes_key_length(self, algorithm)
  173. if not isinstance(algorithm, BlockCipherAlgorithm):
  174. raise UnsupportedAlgorithm(
  175. "GCM requires a block cipher algorithm",
  176. _Reasons.UNSUPPORTED_CIPHER,
  177. )
  178. block_size_bytes = algorithm.block_size // 8
  179. if self._tag is not None and len(self._tag) > block_size_bytes:
  180. raise ValueError(
  181. "Authentication tag cannot be more than {} bytes.".format(
  182. block_size_bytes
  183. )
  184. )