From 75c1485974c2e0331f802dc46bbbf1d4789df946 Mon Sep 17 00:00:00 2001 From: Isaiah Inuwa Date: Thu, 19 Feb 2026 11:54:00 -0600 Subject: [PATCH] Reorganize unsafe code blocks --- .../win_webauthn/src/plugin/crypto.rs | 57 +++++++++++-------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/apps/desktop/desktop_native/win_webauthn/src/plugin/crypto.rs b/apps/desktop/desktop_native/win_webauthn/src/plugin/crypto.rs index 7eb8cd27c8e..42e5daa790a 100644 --- a/apps/desktop/desktop_native/win_webauthn/src/plugin/crypto.rs +++ b/apps/desktop/desktop_native/win_webauthn/src/plugin/crypto.rs @@ -196,36 +196,47 @@ fn verify_signature( /// Calculate a SHA-256 hash over some data. pub(super) fn hash_sha256(data: &[u8]) -> Result, windows::core::Error> { - unsafe { - // Hash data - let sha256 = BcryptHash::sha256()?; - BCryptHashData(sha256.handle, data, 0).ok()?; + // Hash data + let sha256 = BcryptHash::sha256()?; + unsafe { BCryptHashData(sha256.handle, data, 0).ok()? }; + { // Get length of SHA256 hash output tracing::debug!("Getting length of hash output"); - let mut hash_output_len_buf = [0; size_of::()]; - let mut bytes_read = 0; - BCryptGetProperty( - BCRYPT_SHA256_ALG_HANDLE.into(), - BCRYPT_HASH_LENGTH, - Some(&mut hash_output_len_buf), - &mut bytes_read, - 0, - ) - .ok()?; + let hash_output_len = { + let mut hash_output_len_buf = [0; size_of::()]; + let mut bytes_read = 0; + unsafe { + BCryptGetProperty( + BCRYPT_SHA256_ALG_HANDLE.into(), + BCRYPT_HASH_LENGTH, + Some(&mut hash_output_len_buf), + &mut bytes_read, + 0, + ) + .ok()?; + } + u32::from_ne_bytes(hash_output_len_buf) as usize + }; - let hash_output_len = u32::from_ne_bytes(hash_output_len_buf) as usize; tracing::debug!(" Length of hash output: {hash_output_len}"); tracing::debug!("Completing hash"); - let mut hash_buffer: Vec> = Vec::with_capacity(hash_output_len); - { - let hash_slice: &mut [u8] = mem::transmute(hash_buffer.spare_capacity_mut()); - BCryptFinishHash(sha256.handle, hash_slice, 0).ok()?; - } - // SAFETY: BCryptFinishHash initializes the buffer - hash_buffer.set_len(hash_output_len); - let hash_buffer: Vec = mem::transmute(hash_buffer); + let hash_buffer: Vec = { + let mut hash_buffer: Vec> = Vec::with_capacity(hash_output_len); + unsafe { + { + // Temporarily treat the buffer byte slice to fit BCryptFinishHash parameter arguments. + let hash_slice: &mut [u8] = mem::transmute(hash_buffer.spare_capacity_mut()); + BCryptFinishHash(sha256.handle, hash_slice, 0).ok()?; + // The hash handle is not usable after calling BCryptFinishHash, drop to clean up internal state. + drop(sha256); + } + // SAFETY: BCryptFinishHash initializes the buffer + hash_buffer.set_len(hash_output_len); + mem::transmute(hash_buffer) + } + }; tracing::debug!(" Hash: {hash_buffer:?}"); Ok(hash_buffer) }