utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. raise ValueError("Null shared key derived from public/private pair.")
  24. return backend._ffi.buffer(buf, keylen[0])[:]
  25. def _calculate_digest_and_algorithm(backend, data, algorithm):
  26. if not isinstance(algorithm, Prehashed):
  27. hash_ctx = hashes.Hash(algorithm, backend)
  28. hash_ctx.update(data)
  29. data = hash_ctx.finalize()
  30. else:
  31. algorithm = algorithm._algorithm
  32. if len(data) != algorithm.digest_size:
  33. raise ValueError(
  34. "The provided data must be the same length as the hash "
  35. "algorithm's digest size."
  36. )
  37. return (data, algorithm)
  38. def _check_not_prehashed(signature_algorithm):
  39. if isinstance(signature_algorithm, Prehashed):
  40. raise TypeError(
  41. "Prehashed is only supported in the sign and verify methods. "
  42. "It cannot be used with signer, verifier or "
  43. "recover_data_from_signature."
  44. )
  45. def _warn_sign_verify_deprecated():
  46. warnings.warn(
  47. "signer and verifier have been deprecated. Please use sign "
  48. "and verify instead.",
  49. utils.PersistentlyDeprecated2017,
  50. stacklevel=3,
  51. )