modes.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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(Mode, 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(Mode, 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(Mode, 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(Mode, 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: Mode, algorithm: CipherAlgorithm) -> None:
  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(
  54. self: ModeWithInitializationVector, algorithm: BlockCipherAlgorithm
  55. ) -> None:
  56. if len(self.initialization_vector) * 8 != algorithm.block_size:
  57. raise ValueError(
  58. "Invalid IV size ({}) for {}.".format(
  59. len(self.initialization_vector), self.name
  60. )
  61. )
  62. def _check_nonce_length(
  63. nonce: bytes, name: str, algorithm: CipherAlgorithm
  64. ) -> None:
  65. if not isinstance(algorithm, BlockCipherAlgorithm):
  66. raise UnsupportedAlgorithm(
  67. f"{name} requires a block cipher algorithm",
  68. _Reasons.UNSUPPORTED_CIPHER,
  69. )
  70. if len(nonce) * 8 != algorithm.block_size:
  71. raise ValueError(
  72. "Invalid nonce size ({}) for {}.".format(len(nonce), name)
  73. )
  74. def _check_iv_and_key_length(
  75. self: ModeWithInitializationVector, algorithm: CipherAlgorithm
  76. ) -> None:
  77. if not isinstance(algorithm, BlockCipherAlgorithm):
  78. raise UnsupportedAlgorithm(
  79. f"{self} requires a block cipher algorithm",
  80. _Reasons.UNSUPPORTED_CIPHER,
  81. )
  82. _check_aes_key_length(self, algorithm)
  83. _check_iv_length(self, algorithm)
  84. class CBC(ModeWithInitializationVector):
  85. name = "CBC"
  86. def __init__(self, initialization_vector: bytes):
  87. utils._check_byteslike("initialization_vector", initialization_vector)
  88. self._initialization_vector = initialization_vector
  89. @property
  90. def initialization_vector(self) -> bytes:
  91. return self._initialization_vector
  92. validate_for_algorithm = _check_iv_and_key_length
  93. class XTS(ModeWithTweak):
  94. name = "XTS"
  95. def __init__(self, tweak: bytes):
  96. utils._check_byteslike("tweak", tweak)
  97. if len(tweak) != 16:
  98. raise ValueError("tweak must be 128-bits (16 bytes)")
  99. self._tweak = tweak
  100. @property
  101. def tweak(self) -> bytes:
  102. return self._tweak
  103. def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
  104. if algorithm.key_size not in (256, 512):
  105. raise ValueError(
  106. "The XTS specification requires a 256-bit key for AES-128-XTS"
  107. " and 512-bit key for AES-256-XTS"
  108. )
  109. class ECB(Mode):
  110. name = "ECB"
  111. validate_for_algorithm = _check_aes_key_length
  112. class OFB(ModeWithInitializationVector):
  113. name = "OFB"
  114. def __init__(self, initialization_vector: bytes):
  115. utils._check_byteslike("initialization_vector", initialization_vector)
  116. self._initialization_vector = initialization_vector
  117. @property
  118. def initialization_vector(self) -> bytes:
  119. return self._initialization_vector
  120. validate_for_algorithm = _check_iv_and_key_length
  121. class CFB(ModeWithInitializationVector):
  122. name = "CFB"
  123. def __init__(self, initialization_vector: bytes):
  124. utils._check_byteslike("initialization_vector", initialization_vector)
  125. self._initialization_vector = initialization_vector
  126. @property
  127. def initialization_vector(self) -> bytes:
  128. return self._initialization_vector
  129. validate_for_algorithm = _check_iv_and_key_length
  130. class CFB8(ModeWithInitializationVector):
  131. name = "CFB8"
  132. def __init__(self, initialization_vector: bytes):
  133. utils._check_byteslike("initialization_vector", initialization_vector)
  134. self._initialization_vector = initialization_vector
  135. @property
  136. def initialization_vector(self) -> bytes:
  137. return self._initialization_vector
  138. validate_for_algorithm = _check_iv_and_key_length
  139. class CTR(ModeWithNonce):
  140. name = "CTR"
  141. def __init__(self, nonce: bytes):
  142. utils._check_byteslike("nonce", nonce)
  143. self._nonce = nonce
  144. @property
  145. def nonce(self) -> bytes:
  146. return self._nonce
  147. def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
  148. _check_aes_key_length(self, algorithm)
  149. _check_nonce_length(self.nonce, self.name, algorithm)
  150. class GCM(ModeWithInitializationVector, ModeWithAuthenticationTag):
  151. name = "GCM"
  152. _MAX_ENCRYPTED_BYTES = (2**39 - 256) // 8
  153. _MAX_AAD_BYTES = (2**64) // 8
  154. def __init__(
  155. self,
  156. initialization_vector: bytes,
  157. tag: typing.Optional[bytes] = None,
  158. min_tag_length: int = 16,
  159. ):
  160. # OpenSSL 3.0.0 constrains GCM IVs to [64, 1024] bits inclusive
  161. # This is a sane limit anyway so we'll enforce it here.
  162. utils._check_byteslike("initialization_vector", initialization_vector)
  163. if len(initialization_vector) < 8 or len(initialization_vector) > 128:
  164. raise ValueError(
  165. "initialization_vector must be between 8 and 128 bytes (64 "
  166. "and 1024 bits)."
  167. )
  168. self._initialization_vector = initialization_vector
  169. if tag is not None:
  170. utils._check_bytes("tag", tag)
  171. if min_tag_length < 4:
  172. raise ValueError("min_tag_length must be >= 4")
  173. if len(tag) < min_tag_length:
  174. raise ValueError(
  175. "Authentication tag must be {} bytes or longer.".format(
  176. min_tag_length
  177. )
  178. )
  179. self._tag = tag
  180. self._min_tag_length = min_tag_length
  181. @property
  182. def tag(self) -> typing.Optional[bytes]:
  183. return self._tag
  184. @property
  185. def initialization_vector(self) -> bytes:
  186. return self._initialization_vector
  187. def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
  188. _check_aes_key_length(self, algorithm)
  189. if not isinstance(algorithm, BlockCipherAlgorithm):
  190. raise UnsupportedAlgorithm(
  191. "GCM requires a block cipher algorithm",
  192. _Reasons.UNSUPPORTED_CIPHER,
  193. )
  194. block_size_bytes = algorithm.block_size // 8
  195. if self._tag is not None and len(self._tag) > block_size_bytes:
  196. raise ValueError(
  197. "Authentication tag cannot be more than {} bytes.".format(
  198. block_size_bytes
  199. )
  200. )