ms-pkca 0.1.0-dev

PKINIT (RFC 4556) client — PA-PK-AS-REQ / PA-PK-AS-REP with X.509 cert + UnPAC-the-hash (pre-alpha)
Documentation
//! RFC 4556 §3.2.3.1 — Octet-String-to-Key derivation used by PKINIT DH mode.
//!
//! `K_truncated = truncate(H(counter | ZZ | OtherInfo), key_length)` iterated as
//! needed with `counter` starting at 0x01.  `OtherInfo` in PKINIT is
//! `pkinit-KDF | client-DH-nonce | AS-DH-nonce | client-name | server-name`
//! (see RFC 4556 §3.2.3.1); we accept it as a caller-provided blob to stay flexible.
//!
//! `H` is chosen by the KDF-Algorithm-Identifier picked in the AS-REP; SHA-1 and
//! SHA-256 are both defined.  Callers select via [`Hash`].

use sha1::Sha1;
use sha2::{Digest, Sha256};

use crate::error::{Error, Result};

#[derive(Debug, Clone, Copy)]
pub enum Hash {
    Sha1,
    Sha256,
}

impl Hash {
    fn digest_len(self) -> usize {
        match self {
            Hash::Sha1 => 20,
            Hash::Sha256 => 32,
        }
    }
    fn hash(self, data: &[u8]) -> Vec<u8> {
        match self {
            Hash::Sha1 => {
                let mut h = Sha1::new();
                h.update(data);
                h.finalize().to_vec()
            }
            Hash::Sha256 => {
                let mut h = Sha256::new();
                h.update(data);
                h.finalize().to_vec()
            }
        }
    }
}

/// Produce `key_bytes` of key material.
///
/// RFC 4556 §3.2.3.1:
/// ```text
/// SP800-56A KDF-style:
///   for i = 1..N:  K_i = H(counter_i || ZZ || OtherInfo)
///   output = leftmost(concat(K_i), keydatalen)
/// ```
pub fn octet_string_to_key(
    hash: Hash,
    zz: &[u8],
    other_info: &[u8],
    key_bytes: usize,
) -> Result<Vec<u8>> {
    if key_bytes == 0 {
        return Err(Error::Kdf("key_bytes = 0".into()));
    }
    let dlen = hash.digest_len();
    let reps = (key_bytes + dlen - 1) / dlen;
    if reps > 0xFFFF_FFFF {
        return Err(Error::Kdf("too much output requested".into()));
    }
    let mut out = Vec::with_capacity(reps * dlen);
    for i in 1..=reps as u32 {
        let mut buf = Vec::with_capacity(4 + zz.len() + other_info.len());
        buf.extend_from_slice(&i.to_be_bytes());
        buf.extend_from_slice(zz);
        buf.extend_from_slice(other_info);
        out.extend_from_slice(&hash.hash(&buf));
    }
    out.truncate(key_bytes);
    Ok(out)
}

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

    #[test]
    fn deterministic_and_length_correct() {
        let k1 = octet_string_to_key(Hash::Sha256, b"ZZ", b"info", 32).unwrap();
        let k2 = octet_string_to_key(Hash::Sha256, b"ZZ", b"info", 32).unwrap();
        assert_eq!(k1, k2);
        assert_eq!(k1.len(), 32);

        // A different counter iteration should extend, not repeat.
        let long = octet_string_to_key(Hash::Sha256, b"ZZ", b"info", 64).unwrap();
        assert_eq!(&long[..32], k1.as_slice());
        assert_ne!(&long[32..], k1.as_slice());
    }
}