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

221 lines
7.1 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! KDFs: HKDF-SHA-2 (`hkdf`), the BLAKE2b-512 KDF and Argon2id (`argon2`).
//!
//! Semantics match the wolfSSL provider exactly, so either provider can
//! derive the same key:
//!
//! - HKDF (RFC 5869); an empty salt means the all-zero salt of hash length,
//! and the output is capped at 255 × hash length.
//! - BLAKE2b-512 KDF: `BLAKE2b-512(ikm || salt || info)` truncated to
//! `length` (at most 64 bytes).
//! - Argon2id v1.3 with the app defaults: 64 MiB, 3 passes, 4 lanes; the salt
//! must be at least 8 bytes and `info` is not used.
use argon2::{Algorithm, Argon2, Params, Version};
use hkdf::Hkdf;
use sha2::{Sha256, Sha384, Sha512};
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::{HashAlgorithm, KdfAlgorithm},
error::CryptoError,
};
/// Argon2id memory cost in KiB (64 MiB), as in the wolfSSL provider.
pub const ARGON2_M_COST_KIB: u32 = 65_536;
/// Argon2id passes.
pub const ARGON2_T_COST: u32 = 3;
/// Argon2id lanes.
pub const ARGON2_P_COST: u32 = 4;
/// Derive `length` bytes from `ikm`.
pub fn derive_key(
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
match algo {
KdfAlgorithm::Sha256 | KdfAlgorithm::Sha384 | KdfAlgorithm::Sha512 => {
hkdf(algo, ikm, salt, info, length)
}
KdfAlgorithm::Blake2b512 => blake2b_kdf(ikm, salt, info, length),
KdfAlgorithm::Argon2id => argon2id(
ikm,
salt,
length,
ARGON2_M_COST_KIB,
ARGON2_T_COST,
ARGON2_P_COST,
),
KdfAlgorithm::Kmac256 => Err(CryptoError::FeatureNotCompiled(algo.name().into())),
}
}
fn hkdf(
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let hash_len = match algo {
KdfAlgorithm::Sha256 => 32,
KdfAlgorithm::Sha384 => 48,
_ => 64,
};
let max_len = 255 * hash_len;
if length > max_len {
return Err(CryptoError::InvalidInput(format!(
"HKDF: requested length {length} exceeds maximum {max_len}"
)));
}
// `None` is the RFC 5869 zero salt, the same as wolfSSL's empty salt.
let salt = if salt.is_empty() { None } else { Some(salt) };
let mut okm = Zeroizing::new(vec![0u8; length]);
let res = match algo {
KdfAlgorithm::Sha256 => Hkdf::<Sha256>::new(salt, ikm).expand(info, &mut okm),
KdfAlgorithm::Sha384 => Hkdf::<Sha384>::new(salt, ikm).expand(info, &mut okm),
_ => Hkdf::<Sha512>::new(salt, ikm).expand(info, &mut okm),
};
res.map_err(|_| CryptoError::InvalidInput("HKDF: output too long".into()))?;
Ok(okm)
}
fn blake2b_kdf(
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
if length > 64 {
return Err(CryptoError::InvalidInput(
"BLAKE2b-512 KDF: requested length exceeds 64 bytes; use HKDF-SHA512".into(),
));
}
let mut input = Zeroizing::new(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 = Zeroizing::new(crate::hash::hash(HashAlgorithm::Blake2b512, &input)?);
Ok(Zeroizing::new(digest[..length].to_vec()))
}
/// Argon2id v1.3 with explicit cost parameters.
///
/// [`derive_key`] uses the app defaults; this entry point exists for tests
/// and for callers that store their own parameters.
pub fn argon2id(
password: &[u8],
salt: &[u8],
length: usize,
m_cost_kib: u32,
t_cost: u32,
p_cost: u32,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
if salt.len() < 8 {
return Err(CryptoError::InvalidInput(
"Argon2id requires at least 8-byte salt".into(),
));
}
let params = Params::new(m_cost_kib, t_cost, p_cost, Some(length))
.map_err(|e| CryptoError::InvalidInput(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::InvalidInput(format!("Argon2id hash error: {e}")))?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn h(s: &str) -> Vec<u8> {
hex::decode(s).unwrap()
}
#[test]
fn hkdf_sha256_rfc5869_tc1() {
let okm = derive_key(
KdfAlgorithm::Sha256,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&h("000102030405060708090a0b0c"),
&h("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.unwrap();
assert_eq!(
hex::encode(&*okm),
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
);
}
#[test]
fn hkdf_sha512_rfc5869_tc1_inputs() {
// Reference value pinned for the wolfSSL HKDF-SHA-512 fix.
let okm = derive_key(
KdfAlgorithm::Sha512,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&h("000102030405060708090a0b0c"),
&h("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.unwrap();
assert_eq!(
hex::encode(&*okm),
"832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c1481579338da362cb8d9f925d7cb"
);
}
#[test]
fn hkdf_empty_salt_is_zero_salt() {
for (algo, n) in [
(KdfAlgorithm::Sha256, 32),
(KdfAlgorithm::Sha384, 48),
(KdfAlgorithm::Sha512, 64),
] {
let a = derive_key(algo, b"ikm", b"", b"info", 32).unwrap();
let b = derive_key(algo, b"ikm", &vec![0u8; n], b"info", 32).unwrap();
assert_eq!(*a, *b);
}
}
#[test]
fn hkdf_length_limit() {
assert!(derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 255 * 32).is_ok());
assert!(matches!(
derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 255 * 32 + 1),
Err(CryptoError::InvalidInput(_))
));
}
#[test]
fn blake2b_kdf_is_hash_of_concatenation() {
let okm = derive_key(KdfAlgorithm::Blake2b512, b"a", b"b", b"c", 64).unwrap();
let digest = crate::hash::hash(HashAlgorithm::Blake2b512, b"abc").unwrap();
assert_eq!(*okm, digest);
let short = derive_key(KdfAlgorithm::Blake2b512, b"a", b"b", b"c", 16).unwrap();
assert_eq!(*short, digest[..16]);
assert!(derive_key(KdfAlgorithm::Blake2b512, b"a", b"", b"", 65).is_err());
}
#[test]
fn argon2id_rules() {
assert!(argon2id(b"pw", b"short", 32, 64, 1, 1).is_err());
let a = argon2id(b"pw", b"saltsalt", 32, 64, 1, 1).unwrap();
let b = argon2id(b"pw", b"saltsalt", 32, 64, 1, 1).unwrap();
assert_eq!(*a, *b);
assert_ne!(*a, *argon2id(b"pw", b"saltsalT", 32, 64, 1, 1).unwrap());
}
#[test]
fn kmac_is_not_compiled() {
assert!(matches!(
derive_key(KdfAlgorithm::Kmac256, b"k", b"", b"", 32),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}