Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/utils.py: 19%
32 statements
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +0000
« prev ^ index » next coverage.py v7.0.1, created at 2022-12-25 06:11 +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)
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 errors_with_text = backend._consume_errors_with_text()
30 raise ValueError("Error computing shared key.", errors_with_text)
32 return backend._ffi.buffer(buf, keylen[0])[:]
35def _calculate_digest_and_algorithm(
36 data: bytes,
37 algorithm: typing.Union[Prehashed, hashes.HashAlgorithm],
38) -> typing.Tuple[bytes, hashes.HashAlgorithm]:
39 if not isinstance(algorithm, Prehashed):
40 hash_ctx = hashes.Hash(algorithm)
41 hash_ctx.update(data)
42 data = hash_ctx.finalize()
43 else:
44 algorithm = algorithm._algorithm
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 )
52 return (data, algorithm)