human_key 0.1.0-alpha.1

Pure Rust implementation of human-derived attribute fingerprinting for cryptographic key derivation.
Documentation
use crate::errors::HkErr;

/// Parameters for human-derived attribute fingerprinting and key derivation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Params {
    /// Argon2 memory size in kibibytes, between 8 * `p_cost` and (2^32)-1.
    pub m_cost: u32,

    /// Argon2 number of iterations, between 1 and (2^32)-1.
    pub t_cost: u32,

    /// Argon2 degree of parallelism, between 1 and (2^24)-1.
    pub p_cost: u32,

    /// Annihilation proof-of-work constraint as a number of leading zero bits.
    pub constraint: u8,

    /// Selection confirmation code character count.
    pub chars: u8,

    /// Optional application context for domain separation.
    pub context: Option<Vec<u8>>,
}

/// Number of synchronization points between lanes per pass.
///
/// Constant not exported by the Argon2 crate, redefined here.
const SYNC_POINTS: usize = 4;

impl Params {
    /// Default memory cost for Argon2.
    pub const DEFAULT_M: u32 = 12288;

    // Minimum number of 1 KiB memory blocks
    const MIN_M: u32 = 2 * SYNC_POINTS as u32;

    /// Default number of iterations (time cost) for Argon2.
    pub const DEFAULT_T: u32 = 3;

    // Minimum number of iterations
    const MIN_T: u32 = 1;

    /// Default degree of parallelism for Argon2.
    pub const DEFAULT_P: u32 = 1;

    // Minimum and maximum number of threads
    const MIN_P: u32 = 1;
    const MAX_P: u32 = 0xFFFFFF;

    /// Default proof-of-work constraint for annihilation.
    pub const DEFAULT_CONSTRAINT: u8 = 16;

    // Minimum constraint
    const MIN_CONSTRAINT: u8 = 1;

    /// Default number of selection confirmation code characters.
    pub const DEFAULT_CHARS: u8 = 6;

    // Minimum and maximum number of confirmation code characters
    const MIN_CHARS: u8 = 3;
    const MAX_CHARS: u8 = 51;

    /// Default parameters.
    ///
    /// Following the OWASP Password Storage Cheat Sheet, and recommended
    /// defaults for the proof-of-work constraint and confirmation code
    /// character count. No application context is applied.
    pub const DEFAULT: Self = Params {
        m_cost: Self::DEFAULT_M,
        t_cost: Self::DEFAULT_T,
        p_cost: Self::DEFAULT_P,
        constraint: Self::DEFAULT_CONSTRAINT,
        chars: Self::DEFAULT_CHARS,
        context: None,
    };

    /// Create new parameters for Human Key derivation.
    ///
    /// Returns the constructed `Params` on success, or an error when any value
    /// falls outside its accepted range.
    ///
    /// # Arguments
    /// - `m_cost`: memory size for Argon2 in 1 KiB blocks.
    /// - `t_cost`: number of iterations (time cost) for Argon2.
    /// - `p_cost`: degree of parallelism for Argon2.
    /// - `constraint`: proof-of-work constraint for annihilation.
    /// - `chars`: number of selection confirmation code characters.
    /// - `context`: application context for domain separation.
    pub fn new(
        m_cost: u32,
        t_cost: u32,
        p_cost: u32,
        constraint: u8,
        chars: Option<u8>,
        context: Option<&[u8]>,
    ) -> Result<Self, HkErr> {
        if m_cost < Self::MIN_M {
            return Err(HkErr::MemoryTooSmall);
        }
        if m_cost < p_cost * 8 {
            return Err(HkErr::MemoryTooSmall);
        }
        if t_cost < Self::MIN_T {
            return Err(HkErr::TimeTooSmall);
        }
        if p_cost < Self::MIN_P {
            return Err(HkErr::ThreadsTooFew);
        }
        if p_cost > Self::MAX_P {
            return Err(HkErr::ThreadsTooMany);
        }
        if constraint < Self::MIN_CONSTRAINT {
            return Err(HkErr::ConstraintTooSmall);
        }
        if let Some(characters) = chars {
            if characters < Self::MIN_CHARS {
                return Err(HkErr::CharsTooFew);
            }
            if characters > Self::MAX_CHARS {
                return Err(HkErr::CharsTooMany);
            }
        }

        Ok(Self {
            m_cost,
            t_cost,
            p_cost,
            constraint,
            chars: chars.unwrap_or(Self::DEFAULT_CHARS),
            context: context.map(|v| v.to_vec()),
        })
    }
}

impl Default for Params {
    fn default() -> Self {
        Params::DEFAULT
    }
}

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

    #[test]
    fn default() {
        let params = Params::default();
        assert_eq!(params.m_cost, Params::DEFAULT_M);
        assert_eq!(params.t_cost, Params::DEFAULT_T);
        assert_eq!(params.p_cost, Params::DEFAULT_P);
        assert_eq!(params.constraint, Params::DEFAULT_CONSTRAINT);
        assert_eq!(params.chars, Params::DEFAULT_CHARS);
        assert_eq!(params.context, None);

        let params = Params::DEFAULT;
        assert_eq!(params.m_cost, Params::DEFAULT_M);
        assert_eq!(params.t_cost, Params::DEFAULT_T);
        assert_eq!(params.p_cost, Params::DEFAULT_P);
        assert_eq!(params.constraint, Params::DEFAULT_CONSTRAINT);
        assert_eq!(params.chars, Params::DEFAULT_CHARS);
        assert_eq!(params.context, None);
    }

    #[test]
    fn new_valid_params() {
        let result = Params::new(12288, 3, 1, 16, Some(5), None);
        assert!(result.is_ok());

        let params = result.unwrap();
        assert_eq!(params.m_cost, 12288);
        assert_eq!(params.t_cost, 3);
        assert_eq!(params.p_cost, 1);
        assert_eq!(params.constraint, 16);
        assert_eq!(params.chars, 5);
        assert_eq!(params.context, None);
    }

    #[test]
    fn new_with_context() {
        let result =
            Params::new(12288, 3, 1, 16, None, Some(b"EOTWS_Variation1"));
        assert!(result.is_ok());

        let params = result.unwrap();
        assert_eq!(params.context, Some(b"EOTWS_Variation1".to_vec()));
    }

    #[test]
    fn m_cost_too_small() {
        let result = Params::new(1, 3, 1, 16, None, None);
        assert_eq!(result.unwrap_err(), HkErr::MemoryTooSmall);
    }

    #[test]
    fn m_cost_too_small_p_cost() {
        // Too low of a m_cost relative to p_cost must result in an error
        let result = Params::new(15, 3, 2, 16, None, None);
        assert_eq!(result.unwrap_err(), HkErr::MemoryTooSmall);
    }

    #[test]
    fn t_cost_too_small() {
        let result = Params::new(12288, 0, 1, 16, None, None);
        assert_eq!(result.unwrap_err(), HkErr::TimeTooSmall);
    }

    #[test]
    fn p_cost_min_p() {
        let result = Params::new(12288, 3, 0, 16, None, None);
        assert_eq!(result.unwrap_err(), HkErr::ThreadsTooFew);
    }

    #[test]
    fn p_cost_max_p() {
        let result = Params::new(0x1000000 * 8, 3, 0x1000000, 16, None, None);
        assert_eq!(result.unwrap_err(), HkErr::ThreadsTooMany);
    }

    #[test]
    fn min_constraint() {
        let result = Params::new(12288, 3, 1, 0, None, None);
        assert_eq!(result.unwrap_err(), HkErr::ConstraintTooSmall);
    }

    #[test]
    fn chars_too_few() {
        let result = Params::new(12288, 3, 1, 16, Some(2), None);
        assert_eq!(result.unwrap_err(), HkErr::CharsTooFew);
    }

    #[test]
    fn chars_too_many() {
        let result = Params::new(12288, 3, 1, 16, Some(52), None);
        assert_eq!(result.unwrap_err(), HkErr::CharsTooMany);
    }
}