Skip to main content

ms_gkdi/
kdf.rs

1//! SP800-108 counter-mode KDF — the one MS-GKDI uses to walk the key tree.
2//!
3//! Each iteration is `HMAC(key, i_be32 ‖ label ‖ 0x00 ‖ context ‖ bitlen_be32)`, concatenated
4//! until `length` bytes are produced.
5
6use hmac::{Hmac, Mac};
7use sha1::Sha1;
8use sha2::{Sha256, Sha384, Sha512};
9
10use crate::{GkdiError, Result};
11
12/// Hash algorithm named in a `KdfParameters` blob.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum HashAlg {
15    Sha1,
16    Sha256,
17    Sha384,
18    Sha512,
19}
20
21impl HashAlg {
22    /// Parse the `SHA512`-style name Windows stores in the KDF parameters.
23    pub fn from_name(name: &str) -> Result<HashAlg> {
24        match name.trim_end_matches('\0').to_ascii_uppercase().as_str() {
25            "SHA1" => Ok(HashAlg::Sha1),
26            "SHA256" => Ok(HashAlg::Sha256),
27            "SHA384" => Ok(HashAlg::Sha384),
28            "SHA512" => Ok(HashAlg::Sha512),
29            other => Err(GkdiError::UnsupportedAlgorithm(other.to_string())),
30        }
31    }
32
33    pub fn name(self) -> &'static str {
34        match self {
35            HashAlg::Sha1 => "SHA1",
36            HashAlg::Sha256 => "SHA256",
37            HashAlg::Sha384 => "SHA384",
38            HashAlg::Sha512 => "SHA512",
39        }
40    }
41
42    pub fn output_len(self) -> usize {
43        match self {
44            HashAlg::Sha1 => 20,
45            HashAlg::Sha256 => 32,
46            HashAlg::Sha384 => 48,
47            HashAlg::Sha512 => 64,
48        }
49    }
50}
51
52macro_rules! hmac_with {
53    ($hash:ty, $key:expr, $data:expr) => {{
54        let mut m = <Hmac<$hash>>::new_from_slice($key).expect("HMAC takes any key length");
55        m.update($data);
56        m.finalize().into_bytes().to_vec()
57    }};
58}
59
60fn hmac_once(alg: HashAlg, key: &[u8], data: &[u8]) -> Vec<u8> {
61    match alg {
62        HashAlg::Sha1 => hmac_with!(Sha1, key, data),
63        HashAlg::Sha256 => hmac_with!(Sha256, key, data),
64        HashAlg::Sha384 => hmac_with!(Sha384, key, data),
65        HashAlg::Sha512 => hmac_with!(Sha512, key, data),
66    }
67}
68
69/// SP800-108 counter-mode KDF with a 32-bit big-endian counter and length in **bits**.
70pub fn sp800_108_counter(
71    alg: HashAlg,
72    secret: &[u8],
73    label: &[u8],
74    context: &[u8],
75    length: usize,
76) -> Vec<u8> {
77    let bit_len = ((length * 8) as u32).to_be_bytes();
78    let mut out = Vec::with_capacity(length + alg.output_len());
79    let mut counter: u32 = 1;
80    while out.len() < length {
81        let mut data = Vec::with_capacity(4 + label.len() + 1 + context.len() + 4);
82        data.extend_from_slice(&counter.to_be_bytes());
83        data.extend_from_slice(label);
84        data.push(0x00);
85        data.extend_from_slice(context);
86        data.extend_from_slice(&bit_len);
87        out.extend_from_slice(&hmac_once(alg, secret, &data));
88        counter += 1;
89    }
90    out.truncate(length);
91    out
92}
93
94/// Legacy short name — kept so callers ported from `dpapi-ng` still compile.
95pub use sp800_108_counter as kdf;
96
97/// `"KDS service\0"` in UTF-16LE — the label every GKDI derivation uses.
98pub fn kds_service_label() -> Vec<u8> {
99    "KDS service\0"
100        .encode_utf16()
101        .flat_map(u16::to_le_bytes)
102        .collect()
103}