utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 cryptography.hazmat.primitives import hashes
  6. from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
  7. if typing.TYPE_CHECKING:
  8. from cryptography.hazmat.backends.openssl.backend import Backend
  9. def _evp_pkey_derive(backend: "Backend", evp_pkey, peer_public_key) -> bytes:
  10. ctx = backend._lib.EVP_PKEY_CTX_new(evp_pkey, backend._ffi.NULL)
  11. backend.openssl_assert(ctx != backend._ffi.NULL)
  12. ctx = backend._ffi.gc(ctx, backend._lib.EVP_PKEY_CTX_free)
  13. res = backend._lib.EVP_PKEY_derive_init(ctx)
  14. backend.openssl_assert(res == 1)
  15. res = backend._lib.EVP_PKEY_derive_set_peer(ctx, peer_public_key._evp_pkey)
  16. backend.openssl_assert(res == 1)
  17. keylen = backend._ffi.new("size_t *")
  18. res = backend._lib.EVP_PKEY_derive(ctx, backend._ffi.NULL, keylen)
  19. backend.openssl_assert(res == 1)
  20. backend.openssl_assert(keylen[0] > 0)
  21. buf = backend._ffi.new("unsigned char[]", keylen[0])
  22. res = backend._lib.EVP_PKEY_derive(ctx, buf, keylen)
  23. if res != 1:
  24. errors_with_text = backend._consume_errors_with_text()
  25. raise ValueError("Error computing shared key.", errors_with_text)
  26. return backend._ffi.buffer(buf, keylen[0])[:]
  27. def _calculate_digest_and_algorithm(
  28. data: bytes,
  29. algorithm: typing.Union[Prehashed, hashes.HashAlgorithm],
  30. ) -> typing.Tuple[bytes, hashes.HashAlgorithm]:
  31. if not isinstance(algorithm, Prehashed):
  32. hash_ctx = hashes.Hash(algorithm)
  33. hash_ctx.update(data)
  34. data = hash_ctx.finalize()
  35. else:
  36. algorithm = algorithm._algorithm
  37. if len(data) != algorithm.digest_size:
  38. raise ValueError(
  39. "The provided data must be the same length as the hash "
  40. "algorithm's digest size."
  41. )
  42. return (data, algorithm)