kbkdf.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 annotations
  5. import typing
  6. from collections.abc import Callable
  7. from cryptography import utils
  8. from cryptography.exceptions import (
  9. AlreadyFinalized,
  10. InvalidKey,
  11. UnsupportedAlgorithm,
  12. _Reasons,
  13. )
  14. from cryptography.hazmat.primitives import (
  15. ciphers,
  16. cmac,
  17. constant_time,
  18. hashes,
  19. hmac,
  20. )
  21. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  22. class Mode(utils.Enum):
  23. CounterMode = "ctr"
  24. class CounterLocation(utils.Enum):
  25. BeforeFixed = "before_fixed"
  26. AfterFixed = "after_fixed"
  27. MiddleFixed = "middle_fixed"
  28. class _KBKDFDeriver:
  29. def __init__(
  30. self,
  31. prf: Callable,
  32. mode: Mode,
  33. length: int,
  34. rlen: int,
  35. llen: int | None,
  36. location: CounterLocation,
  37. break_location: int | None,
  38. label: bytes | None,
  39. context: bytes | None,
  40. fixed: bytes | None,
  41. ):
  42. assert callable(prf)
  43. if not isinstance(mode, Mode):
  44. raise TypeError("mode must be of type Mode")
  45. if not isinstance(location, CounterLocation):
  46. raise TypeError("location must be of type CounterLocation")
  47. if break_location is None and location is CounterLocation.MiddleFixed:
  48. raise ValueError("Please specify a break_location")
  49. if (
  50. break_location is not None
  51. and location != CounterLocation.MiddleFixed
  52. ):
  53. raise ValueError(
  54. "break_location is ignored when location is not"
  55. " CounterLocation.MiddleFixed"
  56. )
  57. if break_location is not None and not isinstance(break_location, int):
  58. raise TypeError("break_location must be an integer")
  59. if break_location is not None and break_location < 0:
  60. raise ValueError("break_location must be a positive integer")
  61. if (label or context) and fixed:
  62. raise ValueError(
  63. "When supplying fixed data, label and context are ignored."
  64. )
  65. if rlen is None or not self._valid_byte_length(rlen):
  66. raise ValueError("rlen must be between 1 and 4")
  67. if llen is None and fixed is None:
  68. raise ValueError("Please specify an llen")
  69. if llen is not None and not isinstance(llen, int):
  70. raise TypeError("llen must be an integer")
  71. if llen == 0:
  72. raise ValueError("llen must be non-zero")
  73. if label is None:
  74. label = b""
  75. if context is None:
  76. context = b""
  77. utils._check_bytes("label", label)
  78. utils._check_bytes("context", context)
  79. self._prf = prf
  80. self._mode = mode
  81. self._length = length
  82. self._rlen = rlen
  83. self._llen = llen
  84. self._location = location
  85. self._break_location = break_location
  86. self._label = label
  87. self._context = context
  88. self._used = False
  89. self._fixed_data = fixed
  90. @staticmethod
  91. def _valid_byte_length(value: int) -> bool:
  92. if not isinstance(value, int):
  93. raise TypeError("value must be of type int")
  94. value_bin = utils.int_to_bytes(1, value)
  95. return 1 <= len(value_bin) <= 4
  96. def derive(
  97. self, key_material: utils.Buffer, prf_output_size: int
  98. ) -> bytes:
  99. if self._used:
  100. raise AlreadyFinalized
  101. utils._check_byteslike("key_material", key_material)
  102. self._used = True
  103. # inverse floor division (equivalent to ceiling)
  104. rounds = -(-self._length // prf_output_size)
  105. output = [b""]
  106. # For counter mode, the number of iterations shall not be
  107. # larger than 2^r-1, where r <= 32 is the binary length of the counter
  108. # This ensures that the counter values used as an input to the
  109. # PRF will not repeat during a particular call to the KDF function.
  110. r_bin = utils.int_to_bytes(1, self._rlen)
  111. if rounds > pow(2, len(r_bin) * 8) - 1:
  112. raise ValueError("There are too many iterations.")
  113. fixed = self._generate_fixed_input()
  114. if self._location == CounterLocation.BeforeFixed:
  115. data_before_ctr = b""
  116. data_after_ctr = fixed
  117. elif self._location == CounterLocation.AfterFixed:
  118. data_before_ctr = fixed
  119. data_after_ctr = b""
  120. else:
  121. if isinstance(
  122. self._break_location, int
  123. ) and self._break_location > len(fixed):
  124. raise ValueError("break_location offset > len(fixed)")
  125. data_before_ctr = fixed[: self._break_location]
  126. data_after_ctr = fixed[self._break_location :]
  127. for i in range(1, rounds + 1):
  128. h = self._prf(key_material)
  129. counter = utils.int_to_bytes(i, self._rlen)
  130. input_data = data_before_ctr + counter + data_after_ctr
  131. h.update(input_data)
  132. output.append(h.finalize())
  133. return b"".join(output)[: self._length]
  134. def _generate_fixed_input(self) -> bytes:
  135. if self._fixed_data and isinstance(self._fixed_data, bytes):
  136. return self._fixed_data
  137. l_val = utils.int_to_bytes(self._length * 8, self._llen)
  138. return b"".join([self._label, b"\x00", self._context, l_val])
  139. class KBKDFHMAC(KeyDerivationFunction):
  140. def __init__(
  141. self,
  142. algorithm: hashes.HashAlgorithm,
  143. mode: Mode,
  144. length: int,
  145. rlen: int,
  146. llen: int | None,
  147. location: CounterLocation,
  148. label: bytes | None,
  149. context: bytes | None,
  150. fixed: bytes | None,
  151. backend: typing.Any = None,
  152. *,
  153. break_location: int | None = None,
  154. ):
  155. if not isinstance(algorithm, hashes.HashAlgorithm):
  156. raise UnsupportedAlgorithm(
  157. "Algorithm supplied is not a supported hash algorithm.",
  158. _Reasons.UNSUPPORTED_HASH,
  159. )
  160. from cryptography.hazmat.backends.openssl.backend import (
  161. backend as ossl,
  162. )
  163. if not ossl.hmac_supported(algorithm):
  164. raise UnsupportedAlgorithm(
  165. "Algorithm supplied is not a supported hmac algorithm.",
  166. _Reasons.UNSUPPORTED_HASH,
  167. )
  168. self._algorithm = algorithm
  169. self._deriver = _KBKDFDeriver(
  170. self._prf,
  171. mode,
  172. length,
  173. rlen,
  174. llen,
  175. location,
  176. break_location,
  177. label,
  178. context,
  179. fixed,
  180. )
  181. def _prf(self, key_material: bytes) -> hmac.HMAC:
  182. return hmac.HMAC(key_material, self._algorithm)
  183. def derive(self, key_material: utils.Buffer) -> bytes:
  184. return self._deriver.derive(key_material, self._algorithm.digest_size)
  185. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  186. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  187. raise InvalidKey
  188. class KBKDFCMAC(KeyDerivationFunction):
  189. def __init__(
  190. self,
  191. algorithm,
  192. mode: Mode,
  193. length: int,
  194. rlen: int,
  195. llen: int | None,
  196. location: CounterLocation,
  197. label: bytes | None,
  198. context: bytes | None,
  199. fixed: bytes | None,
  200. backend: typing.Any = None,
  201. *,
  202. break_location: int | None = None,
  203. ):
  204. if not issubclass(
  205. algorithm, ciphers.BlockCipherAlgorithm
  206. ) or not issubclass(algorithm, ciphers.CipherAlgorithm):
  207. raise UnsupportedAlgorithm(
  208. "Algorithm supplied is not a supported cipher algorithm.",
  209. _Reasons.UNSUPPORTED_CIPHER,
  210. )
  211. self._algorithm = algorithm
  212. self._cipher: ciphers.BlockCipherAlgorithm | None = None
  213. self._deriver = _KBKDFDeriver(
  214. self._prf,
  215. mode,
  216. length,
  217. rlen,
  218. llen,
  219. location,
  220. break_location,
  221. label,
  222. context,
  223. fixed,
  224. )
  225. def _prf(self, _: bytes) -> cmac.CMAC:
  226. assert self._cipher is not None
  227. return cmac.CMAC(self._cipher)
  228. def derive(self, key_material: utils.Buffer) -> bytes:
  229. self._cipher = self._algorithm(key_material)
  230. assert self._cipher is not None
  231. from cryptography.hazmat.backends.openssl.backend import (
  232. backend as ossl,
  233. )
  234. if not ossl.cmac_algorithm_supported(self._cipher):
  235. raise UnsupportedAlgorithm(
  236. "Algorithm supplied is not a supported cipher algorithm.",
  237. _Reasons.UNSUPPORTED_CIPHER,
  238. )
  239. return self._deriver.derive(key_material, self._cipher.block_size // 8)
  240. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  241. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  242. raise InvalidKey