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. from __future__ import absolute_import, division, print_function
  5. import warnings
  6. from cryptography import utils
  7. from cryptography.hazmat.primitives import hashes
  8. from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
  9. def _evp_pkey_derive(backend, evp_pkey, peer_public_key):
  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. raise ValueError("Null shared key derived from public/private pair.")
  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 or verifier."
  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. )