lum_ccc_rust/crates/ccc-crypto-wolfssl/src/kdf.rs

263 lines
10 KiB
Rust

//! 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)` computed with wolfSSL HMAC
//! (`wc_Tls13_HKDF_Extract` rejects SHA-512, so it is not used).
//! - **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<Zeroizing<Vec<u8>>, 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).
///
/// Both steps are implemented in Rust using wolfSSL's HMAC primitives.
fn hkdf(
hash_type: i32,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, 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)` (RFC 5869 §2.2).
///
/// Computed with wolfSSL's HMAC directly. `wc_Tls13_HKDF_Extract` was used
/// before, but it rejects SHA-512 in this build (BAD_FUNC_ARG), so
/// HKDF-SHA-512, the CCC v2 key schedule, failed on every call.
fn hkdf_extract(
hash_type: i32,
salt: &[u8],
ikm: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let hash_len = hash_output_len(hash_type);
let prk = crate::mac::hmac(hash_type, salt, ikm, hash_len)?;
Ok(Zeroizing::new(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<Zeroizing<Vec<u8>>, 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<Zeroizing<Vec<u8>>, 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<Zeroizing<Vec<u8>>, 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)
}
#[cfg(test)]
mod hkdf_tests {
use super::*;
fn rfc5869_case1(algo: KdfAlgorithm) -> String {
let ikm = [0x0bu8; 22];
let salt: Vec<u8> = (0u8..13).collect();
let info: Vec<u8> = (0xf0u8..0xfa).collect();
let okm = derive_key(algo, &ikm, &salt, &info, 42).unwrap();
okm.iter().map(|b| format!("{b:02x}")).collect()
}
#[test]
fn hkdf_sha256_matches_rfc5869() {
assert_eq!(
rfc5869_case1(KdfAlgorithm::Sha256),
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
);
}
#[test]
fn hkdf_sha512_matches_reference() {
// RFC 5869 case 1 inputs with SHA-512 (computed with Python's hmac).
assert_eq!(
rfc5869_case1(KdfAlgorithm::Sha512),
"832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c1481579338da362cb8d9f925d7cb"
);
}
}