Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/utils.py: 18%
34 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:36 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:36 +0000
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.
5import typing
7from cryptography.hazmat.primitives import hashes
8from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
10if typing.TYPE_CHECKING:
11 from cryptography.hazmat.backends.openssl.backend import Backend
14def _evp_pkey_derive(backend: "Backend", evp_pkey, peer_public_key) -> bytes:
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)
21 if backend._lib.Cryptography_HAS_EVP_PKEY_SET_PEER_EX:
22 res = backend._lib.EVP_PKEY_derive_set_peer_ex(
23 ctx, peer_public_key._evp_pkey, 0
24 )
25 else:
26 res = backend._lib.EVP_PKEY_derive_set_peer(
27 ctx, peer_public_key._evp_pkey
28 )
29 backend.openssl_assert(res == 1)
31 keylen = backend._ffi.new("size_t *")
32 res = backend._lib.EVP_PKEY_derive(ctx, backend._ffi.NULL, keylen)
33 backend.openssl_assert(res == 1)
34 backend.openssl_assert(keylen[0] > 0)
35 buf = backend._ffi.new("unsigned char[]", keylen[0])
36 res = backend._lib.EVP_PKEY_derive(ctx, buf, keylen)
37 if res != 1:
38 errors = backend._consume_errors()
39 raise ValueError("Error computing shared key.", errors)
41 return backend._ffi.buffer(buf, keylen[0])[:]
44def _calculate_digest_and_algorithm(
45 data: bytes,
46 algorithm: typing.Union[Prehashed, hashes.HashAlgorithm],
47) -> typing.Tuple[bytes, hashes.HashAlgorithm]:
48 if not isinstance(algorithm, Prehashed):
49 hash_ctx = hashes.Hash(algorithm)
50 hash_ctx.update(data)
51 data = hash_ctx.finalize()
52 else:
53 algorithm = algorithm._algorithm
55 if len(data) != algorithm.digest_size:
56 raise ValueError(
57 "The provided data must be the same length as the hash "
58 "algorithm's digest size."
59 )
61 return (data, algorithm)