kbkdf.py 8.1 KB

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