From a3a07d3080308d9def359f491e3ad3f5e0b09e57 Mon Sep 17 00:00:00 2001 From: Alex Gaynor Date: Sat, 20 Jul 2024 17:08:27 -0400 Subject: [PATCH] Migrate checking if a hash is supported to Rust --- .../hazmat/backends/openssl/backend.py | 14 +------------- .../hazmat/bindings/_rust/openssl/hashes.pyi | 2 ++ src/rust/src/backend/hashes.rs | 7 ++++++- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py index c87d3e848236..d31b039add0e 100644 --- a/src/cryptography/hazmat/backends/openssl/backend.py +++ b/src/cryptography/hazmat/backends/openssl/backend.py @@ -101,23 +101,11 @@ def openssl_version_text(self) -> str: def openssl_version_number(self) -> int: return rust_openssl.openssl_version() - def _evp_md_from_algorithm(self, algorithm: hashes.HashAlgorithm): - if algorithm.name in ("blake2b", "blake2s"): - alg = f"{algorithm.name}{algorithm.digest_size * 8}".encode( - "ascii" - ) - else: - alg = algorithm.name.encode("ascii") - - evp_md = self._lib.EVP_get_digestbyname(alg) - return evp_md - def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: if self._fips_enabled and not isinstance(algorithm, self._fips_hashes): return False - evp_md = self._evp_md_from_algorithm(algorithm) - return evp_md != self._ffi.NULL + return rust_openssl.hashes.hash_supported(algorithm) def signature_hash_supported( self, algorithm: hashes.HashAlgorithm diff --git a/src/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi b/src/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi index ca5f42a00615..56f317001629 100644 --- a/src/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi +++ b/src/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi @@ -15,3 +15,5 @@ class Hash(hashes.HashContext): def update(self, data: bytes) -> None: ... def finalize(self) -> bytes: ... def copy(self) -> Hash: ... + +def hash_supported(algorithm: hashes.HashAlgorithm) -> bool: ... diff --git a/src/rust/src/backend/hashes.rs b/src/rust/src/backend/hashes.rs index 4226b4b7dbb9..e6c86e92514c 100644 --- a/src/rust/src/backend/hashes.rs +++ b/src/rust/src/backend/hashes.rs @@ -72,6 +72,11 @@ pub(crate) fn message_digest_from_algorithm( } } +#[pyo3::pyfunction] +fn hash_supported(py: pyo3::Python<'_>, algorithm: pyo3::Bound<'_, pyo3::PyAny>) -> bool { + message_digest_from_algorithm(py, &algorithm).is_ok() +} + impl Hash { pub(crate) fn update_bytes(&mut self, data: &[u8]) -> CryptographyResult<()> { self.get_mut_ctx()?.update(data)?; @@ -141,5 +146,5 @@ impl Hash { #[pyo3::pymodule] pub(crate) mod hashes { #[pymodule_export] - use super::Hash; + use super::{hash_supported, Hash}; }