utils.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 warnings
  5. from cryptography import utils
  6. from cryptography.hazmat.primitives import hashes
  7. from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
  8. def _evp_pkey_derive(backend, evp_pkey, peer_public_key):
  9. ctx = backend._lib.EVP_PKEY_CTX_new(evp_pkey, backend._ffi.NULL)
  10. backend.openssl_assert(ctx != backend._ffi.NULL)
  11. ctx = backend._ffi.gc(ctx, backend._lib.EVP_PKEY_CTX_free)
  12. res = backend._lib.EVP_PKEY_derive_init(ctx)
  13. backend.openssl_assert(res == 1)
  14. res = backend._lib.EVP_PKEY_derive_set_peer(ctx, peer_public_key._evp_pkey)
  15. backend.openssl_assert(res == 1)
  16. keylen = backend._ffi.new("size_t *")
  17. res = backend._lib.EVP_PKEY_derive(ctx, backend._ffi.NULL, keylen)
  18. backend.openssl_assert(res == 1)
  19. backend.openssl_assert(keylen[0] > 0)
  20. buf = backend._ffi.new("unsigned char[]", keylen[0])
  21. res = backend._lib.EVP_PKEY_derive(ctx, buf, keylen)
  22. if res != 1:
  23. errors_with_text = backend._consume_errors_with_text()
  24. raise ValueError("Error computing shared key.", errors_with_text)
  25. return backend._ffi.buffer(buf, keylen[0])[:]
  26. def _calculate_digest_and_algorithm(backend, data, algorithm):
  27. if not isinstance(algorithm, Prehashed):
  28. hash_ctx = hashes.Hash(algorithm, backend)
  29. hash_ctx.update(data)
  30. data = hash_ctx.finalize()
  31. else:
  32. algorithm = algorithm._algorithm
  33. if len(data) != algorithm.digest_size:
  34. raise ValueError(
  35. "The provided data must be the same length as the hash "
  36. "algorithm's digest size."
  37. )
  38. return (data, algorithm)
  39. def _check_not_prehashed(signature_algorithm):
  40. if isinstance(signature_algorithm, Prehashed):
  41. raise TypeError(
  42. "Prehashed is only supported in the sign and verify methods. "
  43. "It cannot be used with signer, verifier or "
  44. "recover_data_from_signature."
  45. )
  46. def _warn_sign_verify_deprecated():
  47. warnings.warn(
  48. "signer and verifier have been deprecated. Please use sign "
  49. "and verify instead.",
  50. utils.PersistentlyDeprecated2017,
  51. stacklevel=3,
  52. )