x963kdf.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 cryptography import utils
  7. from cryptography.exceptions import AlreadyFinalized, InvalidKey
  8. from cryptography.hazmat.primitives import constant_time, hashes
  9. from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
  10. def _int_to_u32be(n: int) -> bytes:
  11. return n.to_bytes(length=4, byteorder="big")
  12. class X963KDF(KeyDerivationFunction):
  13. def __init__(
  14. self,
  15. algorithm: hashes.HashAlgorithm,
  16. length: int,
  17. sharedinfo: bytes | None,
  18. backend: typing.Any = None,
  19. ):
  20. max_len = algorithm.digest_size * (2**32 - 1)
  21. if length > max_len:
  22. raise ValueError(f"Cannot derive keys larger than {max_len} bits.")
  23. if sharedinfo is not None:
  24. utils._check_bytes("sharedinfo", sharedinfo)
  25. self._algorithm = algorithm
  26. self._length = length
  27. self._sharedinfo = sharedinfo
  28. self._used = False
  29. def derive(self, key_material: bytes) -> bytes:
  30. if self._used:
  31. raise AlreadyFinalized
  32. self._used = True
  33. utils._check_byteslike("key_material", key_material)
  34. output = [b""]
  35. outlen = 0
  36. counter = 1
  37. while self._length > outlen:
  38. h = hashes.Hash(self._algorithm)
  39. h.update(key_material)
  40. h.update(_int_to_u32be(counter))
  41. if self._sharedinfo is not None:
  42. h.update(self._sharedinfo)
  43. output.append(h.finalize())
  44. outlen += len(output[-1])
  45. counter += 1
  46. return b"".join(output)[: self._length]
  47. def verify(self, key_material: bytes, expected_key: bytes) -> None:
  48. if not constant_time.bytes_eq(self.derive(key_material), expected_key):
  49. raise InvalidKey