1use hmac::{Hmac, Mac};
7use sha1::Sha1;
8use sha2::{Sha256, Sha384, Sha512};
9
10use crate::{DpapiError, Result};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum HashAlg {
15 Sha1,
16 Sha256,
17 Sha384,
18 Sha512,
19}
20
21impl HashAlg {
22 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(DpapiError::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
69pub fn kdf(alg: HashAlg, secret: &[u8], label: &[u8], context: &[u8], length: usize) -> Vec<u8> {
71 let bit_len = ((length * 8) as u32).to_be_bytes();
72 let mut out = Vec::with_capacity(length + alg.output_len());
73 let mut counter: u32 = 1;
74 while out.len() < length {
75 let mut data = Vec::with_capacity(4 + label.len() + 1 + context.len() + 4);
76 data.extend_from_slice(&counter.to_be_bytes());
77 data.extend_from_slice(label);
78 data.push(0x00);
79 data.extend_from_slice(context);
80 data.extend_from_slice(&bit_len);
81 out.extend_from_slice(&hmac_once(alg, secret, &data));
82 counter += 1;
83 }
84 out.truncate(length);
85 out
86}
87
88pub fn kds_service_label() -> Vec<u8> {
90 "KDS service\0"
91 .encode_utf16()
92 .flat_map(u16::to_le_bytes)
93 .collect()
94}