• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(
21        ctx, peer_public_key._evp_pkey
22    )
23    backend.openssl_assert(res == 1)
24    keylen = backend._ffi.new("size_t *")
25    res = backend._lib.EVP_PKEY_derive(ctx, backend._ffi.NULL, keylen)
26    backend.openssl_assert(res == 1)
27    backend.openssl_assert(keylen[0] > 0)
28    buf = backend._ffi.new("unsigned char[]", keylen[0])
29    res = backend._lib.EVP_PKEY_derive(ctx, buf, keylen)
30    if res != 1:
31        raise ValueError(
32            "Null shared key derived from public/private pair."
33        )
34
35    return backend._ffi.buffer(buf, keylen[0])[:]
36
37
38def _calculate_digest_and_algorithm(backend, data, algorithm):
39    if not isinstance(algorithm, Prehashed):
40        hash_ctx = hashes.Hash(algorithm, backend)
41        hash_ctx.update(data)
42        data = hash_ctx.finalize()
43    else:
44        algorithm = algorithm._algorithm
45
46    if len(data) != algorithm.digest_size:
47        raise ValueError(
48            "The provided data must be the same length as the hash "
49            "algorithm's digest size."
50        )
51
52    return (data, algorithm)
53
54
55def _check_not_prehashed(signature_algorithm):
56    if isinstance(signature_algorithm, Prehashed):
57        raise TypeError(
58            "Prehashed is only supported in the sign and verify methods. "
59            "It cannot be used with signer or verifier."
60        )
61
62
63def _warn_sign_verify_deprecated():
64    warnings.warn(
65        "signer and verifier have been deprecated. Please use sign "
66        "and verify instead.",
67        utils.PersistentlyDeprecated,
68        stacklevel=3
69    )
70