kbkdf.py 7.5 KB

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