hkdf.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. import six
  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, hmac
  16. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  17. @utils.register_interface(KeyDerivationFunction)
  18. class HKDF(object):
  19. def __init__(self, algorithm, length, salt, info, backend=None):
  20. backend = _get_backend(backend)
  21. if not isinstance(backend, HMACBackend):
  22. raise UnsupportedAlgorithm(
  23. "Backend object does not implement HMACBackend.",
  24. _Reasons.BACKEND_MISSING_INTERFACE,
  25. )
  26. self._algorithm = algorithm
  27. if salt is None:
  28. salt = b"\x00" * self._algorithm.digest_size
  29. else:
  30. utils._check_bytes("salt", salt)
  31. self._salt = salt
  32. self._backend = backend
  33. self._hkdf_expand = HKDFExpand(self._algorithm, length, info, backend)
  34. def _extract(self, key_material):
  35. h = hmac.HMAC(self._salt, self._algorithm, backend=self._backend)
  36. h.update(key_material)
  37. return h.finalize()
  38. def derive(self, key_material):
  39. utils._check_byteslike("key_material", key_material)
  40. return self._hkdf_expand.derive(self._extract(key_material))
  41. def verify(self, key_material, expected_key):
  42. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  43. raise InvalidKey
  44. @utils.register_interface(KeyDerivationFunction)
  45. class HKDFExpand(object):
  46. def __init__(self, algorithm, length, info, backend=None):
  47. backend = _get_backend(backend)
  48. if not isinstance(backend, HMACBackend):
  49. raise UnsupportedAlgorithm(
  50. "Backend object does not implement HMACBackend.",
  51. _Reasons.BACKEND_MISSING_INTERFACE,
  52. )
  53. self._algorithm = algorithm
  54. self._backend = backend
  55. max_length = 255 * algorithm.digest_size
  56. if length > max_length:
  57. raise ValueError(
  58. "Can not derive keys larger than {} octets.".format(max_length)
  59. )
  60. self._length = length
  61. if info is None:
  62. info = b""
  63. else:
  64. utils._check_bytes("info", info)
  65. self._info = info
  66. self._used = False
  67. def _expand(self, key_material):
  68. output = [b""]
  69. counter = 1
  70. while self._algorithm.digest_size * (len(output) - 1) < self._length:
  71. h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
  72. h.update(output[-1])
  73. h.update(self._info)
  74. h.update(six.int2byte(counter))
  75. output.append(h.finalize())
  76. counter += 1
  77. return b"".join(output)[: self._length]
  78. def derive(self, key_material):
  79. utils._check_byteslike("key_material", key_material)
  80. if self._used:
  81. raise AlreadyFinalized
  82. self._used = True
  83. return self._expand(key_material)
  84. def verify(self, key_material, expected_key):
  85. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  86. raise InvalidKey