concatkdf.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 annotations
  5. import typing
  6. from collections.abc import Callable
  7. from cryptography import utils
  8. from cryptography.exceptions import AlreadyFinalized, InvalidKey
  9. from cryptography.hazmat.primitives import constant_time, hashes, hmac
  10. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  11. def _int_to_u32be(n: int) -> bytes:
  12. return n.to_bytes(length=4, byteorder="big")
  13. def _common_args_checks(
  14. algorithm: hashes.HashAlgorithm,
  15. length: int,
  16. otherinfo: bytes | None,
  17. ) -> None:
  18. max_length = algorithm.digest_size * (2**32 - 1)
  19. if length > max_length:
  20. raise ValueError(f"Cannot derive keys larger than {max_length} bits.")
  21. if otherinfo is not None:
  22. utils._check_bytes("otherinfo", otherinfo)
  23. def _concatkdf_derive(
  24. key_material: utils.Buffer,
  25. length: int,
  26. auxfn: Callable[[], hashes.HashContext],
  27. otherinfo: bytes,
  28. ) -> bytes:
  29. utils._check_byteslike("key_material", key_material)
  30. output = [b""]
  31. outlen = 0
  32. counter = 1
  33. while length > outlen:
  34. h = auxfn()
  35. h.update(_int_to_u32be(counter))
  36. h.update(key_material)
  37. h.update(otherinfo)
  38. output.append(h.finalize())
  39. outlen += len(output[-1])
  40. counter += 1
  41. return b"".join(output)[:length]
  42. class ConcatKDFHash(KeyDerivationFunction):
  43. def __init__(
  44. self,
  45. algorithm: hashes.HashAlgorithm,
  46. length: int,
  47. otherinfo: bytes | None,
  48. backend: typing.Any = None,
  49. ):
  50. _common_args_checks(algorithm, length, otherinfo)
  51. self._algorithm = algorithm
  52. self._length = length
  53. self._otherinfo: bytes = otherinfo if otherinfo is not None else b""
  54. self._used = False
  55. def _hash(self) -> hashes.Hash:
  56. return hashes.Hash(self._algorithm)
  57. def derive(self, key_material: utils.Buffer) -> bytes:
  58. if self._used:
  59. raise AlreadyFinalized
  60. self._used = True
  61. return _concatkdf_derive(
  62. key_material, self._length, self._hash, self._otherinfo
  63. )
  64. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  65. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  66. raise InvalidKey
  67. class ConcatKDFHMAC(KeyDerivationFunction):
  68. def __init__(
  69. self,
  70. algorithm: hashes.HashAlgorithm,
  71. length: int,
  72. salt: bytes | None,
  73. otherinfo: bytes | None,
  74. backend: typing.Any = None,
  75. ):
  76. _common_args_checks(algorithm, length, otherinfo)
  77. self._algorithm = algorithm
  78. self._length = length
  79. self._otherinfo: bytes = otherinfo if otherinfo is not None else b""
  80. if algorithm.block_size is None:
  81. raise TypeError(f"{algorithm.name} is unsupported for ConcatKDF")
  82. if salt is None:
  83. salt = b"\x00" * algorithm.block_size
  84. else:
  85. utils._check_bytes("salt", salt)
  86. self._salt = salt
  87. self._used = False
  88. def _hmac(self) -> hmac.HMAC:
  89. return hmac.HMAC(self._salt, self._algorithm)
  90. def derive(self, key_material: utils.Buffer) -> bytes:
  91. if self._used:
  92. raise AlreadyFinalized
  93. self._used = True
  94. return _concatkdf_derive(
  95. key_material, self._length, self._hmac, self._otherinfo
  96. )
  97. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  98. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  99. raise InvalidKey