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