kbkdf.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 enum import Enum
  6. from cryptography import utils
  7. from cryptography.exceptions import (
  8. AlreadyFinalized,
  9. InvalidKey,
  10. UnsupportedAlgorithm,
  11. _Reasons,
  12. )
  13. from cryptography.hazmat.backends import _get_backend
  14. from cryptography.hazmat.backends.interfaces import HMACBackend
  15. from cryptography.hazmat.primitives import constant_time, hashes, hmac
  16. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  17. class Mode(Enum):
  18. CounterMode = "ctr"
  19. class CounterLocation(Enum):
  20. BeforeFixed = "before_fixed"
  21. AfterFixed = "after_fixed"
  22. class KBKDFHMAC(KeyDerivationFunction):
  23. def __init__(
  24. self,
  25. algorithm: hashes.HashAlgorithm,
  26. mode: Mode,
  27. length: int,
  28. rlen: int,
  29. llen: typing.Optional[int],
  30. location: CounterLocation,
  31. label: typing.Optional[bytes],
  32. context: typing.Optional[bytes],
  33. fixed: typing.Optional[bytes],
  34. backend=None,
  35. ):
  36. backend = _get_backend(backend)
  37. if not isinstance(backend, HMACBackend):
  38. raise UnsupportedAlgorithm(
  39. "Backend object does not implement HMACBackend.",
  40. _Reasons.BACKEND_MISSING_INTERFACE,
  41. )
  42. if not isinstance(algorithm, hashes.HashAlgorithm):
  43. raise UnsupportedAlgorithm(
  44. "Algorithm supplied is not a supported hash algorithm.",
  45. _Reasons.UNSUPPORTED_HASH,
  46. )
  47. if not backend.hmac_supported(algorithm):
  48. raise UnsupportedAlgorithm(
  49. "Algorithm supplied is not a supported hmac algorithm.",
  50. _Reasons.UNSUPPORTED_HASH,
  51. )
  52. if not isinstance(mode, Mode):
  53. raise TypeError("mode must be of type Mode")
  54. if not isinstance(location, CounterLocation):
  55. raise TypeError("location must be of type CounterLocation")
  56. if (label or context) and fixed:
  57. raise ValueError(
  58. "When supplying fixed data, " "label and context are ignored."
  59. )
  60. if rlen is None or not self._valid_byte_length(rlen):
  61. raise ValueError("rlen must be between 1 and 4")
  62. if llen is None and fixed is None:
  63. raise ValueError("Please specify an llen")
  64. if llen is not None and not isinstance(llen, int):
  65. raise TypeError("llen must be an integer")
  66. if label is None:
  67. label = b""
  68. if context is None:
  69. context = b""
  70. utils._check_bytes("label", label)
  71. utils._check_bytes("context", context)
  72. self._algorithm = algorithm
  73. self._mode = mode
  74. self._length = length
  75. self._rlen = rlen
  76. self._llen = llen
  77. self._location = location
  78. self._label = label
  79. self._context = context
  80. self._backend = backend
  81. self._used = False
  82. self._fixed_data = fixed
  83. def _valid_byte_length(self, value: int) -> bool:
  84. if not isinstance(value, int):
  85. raise TypeError("value must be of type int")
  86. value_bin = utils.int_to_bytes(1, value)
  87. if not 1 <= len(value_bin) <= 4:
  88. return False
  89. return True
  90. def derive(self, key_material: bytes) -> bytes:
  91. if self._used:
  92. raise AlreadyFinalized
  93. utils._check_byteslike("key_material", key_material)
  94. self._used = True
  95. # inverse floor division (equivalent to ceiling)
  96. rounds = -(-self._length // self._algorithm.digest_size)
  97. output = [b""]
  98. # For counter mode, the number of iterations shall not be
  99. # larger than 2^r-1, where r <= 32 is the binary length of the counter
  100. # This ensures that the counter values used as an input to the
  101. # PRF will not repeat during a particular call to the KDF function.
  102. r_bin = utils.int_to_bytes(1, self._rlen)
  103. if rounds > pow(2, len(r_bin) * 8) - 1:
  104. raise ValueError("There are too many iterations.")
  105. for i in range(1, rounds + 1):
  106. h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
  107. counter = utils.int_to_bytes(i, self._rlen)
  108. if self._location == CounterLocation.BeforeFixed:
  109. h.update(counter)
  110. h.update(self._generate_fixed_input())
  111. if self._location == CounterLocation.AfterFixed:
  112. h.update(counter)
  113. output.append(h.finalize())
  114. return b"".join(output)[: self._length]
  115. def _generate_fixed_input(self) -> bytes:
  116. if self._fixed_data and isinstance(self._fixed_data, bytes):
  117. return self._fixed_data
  118. l_val = utils.int_to_bytes(self._length * 8, self._llen)
  119. return b"".join([self._label, b"\x00", self._context, l_val])
  120. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  121. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  122. raise InvalidKey