pqbox 1.1.0

Post-quantum crypto toolkit: hybrid ML-KEM-1024 + P-384 sealed boxes, composite ML-DSA-87 signatures, an opt-in paranoid suite adding Classic McEliece and SLH-DSA, AEAD, KDF, hashing and Argon2id
Documentation
//! Key derivation and MACs: HKDF-SHA-256 (`hkdf`, RFC 5869) and HMAC-SHA-256 (`hmac`, RFC 2104).

use hkdf::Hkdf;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use zeroize::Zeroizing;

use crate::{Error, Result};

/// Largest HKDF-SHA-256 output: 255 blocks of 32 bytes.
pub const HKDF_MAX_LEN: usize = 255 * 32;
/// HMAC-SHA-256 tag length.
pub const HMAC_LEN: usize = 32;

/// HKDF-SHA-256 (extract then expand) to `len` bytes. An empty `salt` means no salt.
///
/// `len` is checked before anything is allocated, so a hostile length costs nothing.
///
/// # Errors
/// [`Error::InvalidParams`] when `len` exceeds [`HKDF_MAX_LEN`].
pub fn hkdf_sha256(ikm: &[u8], salt: &[u8], info: &[u8], len: usize) -> Result<Zeroizing<Vec<u8>>> {
    if len > HKDF_MAX_LEN {
        return Err(Error::InvalidParams("HKDF output too long"));
    }
    let mut out = Zeroizing::new(vec![0u8; len]);
    hkdf_sha256_into(ikm, salt, &[info], &mut out)?;
    Ok(out)
}

/// HKDF-SHA-256 into `out`, with `info` given as parts that are concatenated.
///
/// # Errors
/// [`Error::InvalidParams`] when `out` is longer than [`HKDF_MAX_LEN`].
pub fn hkdf_sha256_into(ikm: &[u8], salt: &[u8], info: &[&[u8]], out: &mut [u8]) -> Result<()> {
    let salt = if salt.is_empty() { None } else { Some(salt) };
    Hkdf::<Sha256>::new(salt, ikm)
        .expand_multi_info(info, out)
        .map_err(|_| Error::InvalidParams("HKDF output too long"))
}

/// HMAC-SHA-256.
///
/// # Errors
/// Never in practice: HMAC accepts keys of any length. The error exists only because the
/// underlying API is fallible.
pub fn hmac_sha256(key: &[u8], message: &[u8]) -> Result<[u8; HMAC_LEN]> {
    let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(key).map_err(|_| Error::InvalidKey)?;
    mac.update(message);
    Ok(mac.finalize().into_bytes().into())
}

/// Checks an HMAC-SHA-256 tag in constant time. Truncated tags are rejected.
#[must_use]
pub fn hmac_sha256_verify(key: &[u8], message: &[u8], tag: &[u8]) -> bool {
    hmac_sha256(key, message).is_ok_and(|t| crate::ct_eq(&t, tag))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hkdf_length_limits() {
        assert_eq!(hkdf_sha256(b"k", b"", b"", HKDF_MAX_LEN).unwrap().len(), HKDF_MAX_LEN);
        assert!(hkdf_sha256(b"k", b"", b"", HKDF_MAX_LEN + 1).is_err());
        assert!(hkdf_sha256(b"k", b"", b"", 0).unwrap().is_empty());
    }

    /// Regression: the length used to be allocated before it was checked, so `usize::MAX`
    /// panicked (capacity overflow) and `2^60` aborted the process (allocation failure).
    #[test]
    fn hkdf_rejects_huge_lengths_before_allocating() {
        for len in [usize::MAX, 1 << 60, 1 << 40, 1 << 31, HKDF_MAX_LEN + 1] {
            assert_eq!(
                hkdf_sha256(b"k", b"", b"", len),
                Err(Error::InvalidParams("HKDF output too long")),
                "len {len}"
            );
        }
    }

    #[test]
    fn hmac_verify() {
        let tag = hmac_sha256(b"key", b"msg").unwrap();
        assert!(hmac_sha256_verify(b"key", b"msg", &tag));
        assert!(!hmac_sha256_verify(b"key", b"msG", &tag));
        assert!(!hmac_sha256_verify(b"key", b"msg", &tag[..31]));
    }
}