kbkdf.py 5.0 KB

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