kbkdf.py 8.9 KB

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