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