//! Key derivation function implementations via wolfCrypt. //! //! Covers HKDF (SHA-256 / SHA-384 / SHA-512), Argon2id, and BLAKE2b-based KDF. //! //! ## HKDF implementation //! //! wolfSSL v5.7.x does not expose a generic `wc_HKDF()` function. The only //! available HKDF primitive is `wc_Tls13_HKDF_Extract` (RFC 5869 Extract step) //! together with the `wc_Hmac*` family. We implement RFC 5869 HKDF in Rust: //! //! - **Extract**: `PRK = HMAC-Hash(salt, IKM)` via `wc_Tls13_HKDF_Extract`. //! - **Expand**: `OKM = T(1)||T(2)||…` where //! `T(i) = HMAC(PRK, T(i-1) || info || i)` computed with wolfSSL HMAC. //! //! ## Argon2id //! //! wolfSSL v5.7.x has no built-in Argon2 implementation, so we delegate to //! the pure-Rust `argon2` crate (which is maintained by RustCrypto). use zeroize::Zeroizing; use ccc_crypto_core::{algorithms::KdfAlgorithm, error::CryptoError}; // wolfCrypt hash type constants from `enum wc_HashType` in types.h (non-FIPS). const WC_HASH_TYPE_SHA256: i32 = 6; const WC_HASH_TYPE_SHA384: i32 = 7; const WC_HASH_TYPE_SHA512: i32 = 8; /// Output byte lengths for each HMAC hash variant, matching the digest size. fn hash_output_len(hash_type: i32) -> usize { match hash_type { WC_HASH_TYPE_SHA256 => 32, WC_HASH_TYPE_SHA384 => 48, WC_HASH_TYPE_SHA512 => 64, _ => 32, } } // ────────────────────────────────────────────────────────────────────────────── // Public entry point // ────────────────────────────────────────────────────────────────────────────── /// Derive a key of `length` bytes from input keying material. pub fn derive_key( algo: KdfAlgorithm, ikm: &[u8], salt: &[u8], info: &[u8], length: usize, ) -> Result>, CryptoError> { match algo { KdfAlgorithm::Sha256 => hkdf(WC_HASH_TYPE_SHA256, ikm, salt, info, length), KdfAlgorithm::Sha384 => hkdf(WC_HASH_TYPE_SHA384, ikm, salt, info, length), KdfAlgorithm::Sha512 => hkdf(WC_HASH_TYPE_SHA512, ikm, salt, info, length), KdfAlgorithm::Blake2b512 => blake2b_kdf(ikm, salt, info, length), KdfAlgorithm::Argon2id => argon2id(ikm, salt, length), KdfAlgorithm::Kmac256 => Err(CryptoError::FeatureNotCompiled("KMAC256 (Phase 5+)".into())), } } // ────────────────────────────────────────────────────────────────────────────── // HKDF (RFC 5869) using wolfCrypt primitives // ────────────────────────────────────────────────────────────────────────────── /// HKDF: Extract then Expand (RFC 5869). /// /// Extract uses `wc_Tls13_HKDF_Extract` (wolfSSL's RFC 5869 Extract). /// Expand is implemented in Rust using wolfSSL's HMAC primitives. fn hkdf( hash_type: i32, ikm: &[u8], salt: &[u8], info: &[u8], length: usize, ) -> Result>, CryptoError> { // ── Extract ────────────────────────────────────────────────────────────── let hash_len = hash_output_len(hash_type); // Use zero-valued salt if none is provided (RFC 5869 §2.2). let default_salt = vec![0u8; hash_len]; let effective_salt = if salt.is_empty() { &default_salt } else { salt }; let prk = hkdf_extract(hash_type, effective_salt, ikm)?; // ── Expand ─────────────────────────────────────────────────────────────── hkdf_expand(hash_type, &prk, info, length) } /// HKDF-Extract: `PRK = HMAC-Hash(salt, IKM)`. /// /// Wraps `wc_Tls13_HKDF_Extract` which takes a mutable IKM pointer. fn hkdf_extract( hash_type: i32, salt: &[u8], ikm: &[u8], ) -> Result>, CryptoError> { let hash_len = hash_output_len(hash_type); let mut prk = Zeroizing::new(vec![0u8; hash_len]); // wolfSSL's wc_Tls13_HKDF_Extract takes `byte* ikm` (mutable), so we // make a writable copy. let mut ikm_buf = ikm.to_vec(); unsafe { let ret = crate::sys::wc_Tls13_HKDF_Extract( prk.as_mut_ptr(), if salt.is_empty() { std::ptr::null() } else { salt.as_ptr() }, salt.len() as u32, ikm_buf.as_mut_ptr(), ikm_buf.len() as u32, hash_type, ); if ret != 0 { return Err(CryptoError::InternalError(format!( "wc_Tls13_HKDF_Extract returned {ret}" ))); } } Ok(prk) } /// HKDF-Expand: `OKM = T(1) || T(2) || …` truncated to `length` bytes. /// /// `T(i) = HMAC(PRK, T(i-1) || info || i)` per RFC 5869 §2.3. /// Uses wolfSSL HMAC via `crate::mac::hmac`. fn hkdf_expand( hash_type: i32, prk: &[u8], info: &[u8], length: usize, ) -> Result>, CryptoError> { let hash_len = hash_output_len(hash_type); // Maximum HKDF output is 255 * HashLen (RFC 5869 §2.3). let max_len = 255 * hash_len; if length > max_len { return Err(CryptoError::InvalidInput(format!( "HKDF: requested length {length} exceeds maximum {max_len}" ))); } let mut okm = Zeroizing::new(vec![0u8; length]); let mut t = Vec::new(); // T(i-1); starts empty per spec let mut pos = 0usize; let mut counter = 1u8; while pos < length { // Build the HMAC input: T(i-1) || info || counter let mut input = Vec::with_capacity(t.len() + info.len() + 1); input.extend_from_slice(&t); input.extend_from_slice(info); input.push(counter); // T(i) = HMAC-Hash(PRK, input) t = crate::mac::hmac(hash_type, prk, &input, hash_len)?; let copy_len = (length - pos).min(hash_len); okm[pos..pos + copy_len].copy_from_slice(&t[..copy_len]); pos += copy_len; counter = counter .checked_add(1) .ok_or_else(|| CryptoError::InternalError("HKDF counter overflow".into()))?; } Ok(okm) } // ────────────────────────────────────────────────────────────────────────────── // BLAKE2b-based KDF // ────────────────────────────────────────────────────────────────────────────── /// BLAKE2b-512 used as a KDF: `BLAKE2b(ikm || salt || info)` → `length` bytes. /// /// This is the same construction the Dart `RatchetEngine._kdf()` uses when /// `kdfFunction == blake2b512`. Output is truncated to `length` bytes. fn blake2b_kdf( ikm: &[u8], salt: &[u8], info: &[u8], length: usize, ) -> Result>, CryptoError> { use crate::hash; use ccc_crypto_core::algorithms::HashAlgorithm; // Concatenate ikm || salt || info and hash the result. let mut input = Vec::with_capacity(ikm.len() + salt.len() + info.len()); input.extend_from_slice(ikm); input.extend_from_slice(salt); input.extend_from_slice(info); let digest = hash::hash(HashAlgorithm::Blake2b512, &input)?; // Truncate or zero-extend to the requested length. // For lengths > 64 (BLAKE2b-512 output) this KDF is not appropriate — // callers should use HKDF-SHA512 instead. if length > digest.len() { return Err(CryptoError::InvalidInput( "BLAKE2b-512 KDF: requested length exceeds 64 bytes; use HKDF-SHA512".into(), )); } let mut out = Zeroizing::new(vec![0u8; length]); out.copy_from_slice(&digest[..length]); Ok(out) } // ────────────────────────────────────────────────────────────────────────────── // Argon2id // ────────────────────────────────────────────────────────────────────────────── /// Argon2id KDF via the pure-Rust `argon2` crate. /// /// wolfSSL v5.7.x has no built-in Argon2 implementation. /// /// Uses the memory and iteration parameters from `DEFAULT_CIPHER_PARAMS` in /// `cipher_constants.dart`: 64 MiB memory, 3 iterations, 4 lanes. fn argon2id( password: &[u8], salt: &[u8], length: usize, ) -> Result>, CryptoError> { // Argon2 requires at least 8 bytes of salt. if salt.len() < 8 { return Err(CryptoError::InvalidInput( "Argon2id requires at least 8-byte salt".into(), )); } use argon2::{Algorithm, Argon2, Params, Version}; // Match DEFAULT_CIPHER_PARAMS in cipher_constants.dart: // argon2_memory_kb: 65536 (64 MiB) // argon2_iterations: 3 // argon2_parallelism: 4 let params = Params::new( 65_536, // m_cost: 64 MiB 3, // t_cost: iterations 4, // p_cost: parallelism (lanes) Some(length), // output length ) .map_err(|e| CryptoError::InternalError(format!("Argon2 params error: {e}")))?; let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); let mut out = Zeroizing::new(vec![0u8; length]); argon2 .hash_password_into(password, salt, &mut out) .map_err(|e| CryptoError::InternalError(format!("Argon2id hash error: {e}")))?; Ok(out) }