Skip to main content

dpapi_offline/
crypto.rs

1//! DPAPI crypto primitives. These are the parts validated against **published RFC
2//! known-answer vectors** (see the tests) — PBKDF2-HMAC-SHA1 (RFC 6070) and HMAC (RFC 2202 /
3//! 4231). The DPAPI-specific derivation that *uses* them lives in `masterkey`/`blob`.
4
5use aes::Aes256;
6use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
7use des::TdesEde3;
8use hmac::{Hmac, Mac};
9use sha1::Sha1;
10use sha2::Sha512;
11
12pub type HmacSha1 = Hmac<Sha1>;
13pub type HmacSha512 = Hmac<Sha512>;
14
15pub fn hmac_sha1(key: &[u8], msg: &[u8]) -> [u8; 20] {
16    let mut m = <HmacSha1 as Mac>::new_from_slice(key).expect("hmac key");
17    m.update(msg);
18    m.finalize().into_bytes().into()
19}
20
21pub fn hmac_sha512(key: &[u8], msg: &[u8]) -> [u8; 64] {
22    let mut m = <HmacSha512 as Mac>::new_from_slice(key).expect("hmac key");
23    m.update(msg);
24    m.finalize().into_bytes().into()
25}
26
27/// Which hash a DPAPI structure selected (from its ALG_ID). Carries the digest and HMAC
28/// block sizes the key-derivation needs.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum HashAlgo {
31    Sha1,
32    Sha512,
33}
34
35impl HashAlgo {
36    /// CALG_SHA1 = 0x8004, CALG_SHA_512 = 0x800e.
37    pub fn from_alg_id(id: u32) -> Option<Self> {
38        match id {
39            0x8004 => Some(HashAlgo::Sha1),
40            0x800e => Some(HashAlgo::Sha512),
41            _ => None,
42        }
43    }
44    pub fn digest_len(self) -> usize {
45        match self {
46            HashAlgo::Sha1 => 20,
47            HashAlgo::Sha512 => 64,
48        }
49    }
50    pub fn block_size(self) -> usize {
51        match self {
52            HashAlgo::Sha1 => 64,
53            HashAlgo::Sha512 => 128,
54        }
55    }
56    pub fn hmac(self, key: &[u8], msg: &[u8]) -> Vec<u8> {
57        match self {
58            HashAlgo::Sha1 => hmac_sha1(key, msg).to_vec(),
59            HashAlgo::Sha512 => hmac_sha512(key, msg).to_vec(),
60        }
61    }
62    /// PBKDF2 with this hash as the PRF.
63    pub fn pbkdf2(self, password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
64        let mut out = vec![0u8; dklen];
65        let rounds = rounds.max(1);
66        match self {
67            HashAlgo::Sha1 => pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, rounds, &mut out),
68            HashAlgo::Sha512 => pbkdf2::pbkdf2_hmac::<Sha512>(password, salt, rounds, &mut out),
69        }
70        out
71    }
72}
73
74/// Which block cipher a DPAPI structure selected (from its ALG_ID).
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum CipherAlgo {
77    Aes256,
78    TripleDes,
79}
80
81impl CipherAlgo {
82    /// CALG_AES_256 = 0x6610, CALG_3DES = 0x6603.
83    pub fn from_alg_id(id: u32) -> Option<Self> {
84        match id {
85            0x6610 => Some(CipherAlgo::Aes256),
86            0x6603 => Some(CipherAlgo::TripleDes),
87            _ => None,
88        }
89    }
90    pub fn key_len(self) -> usize {
91        match self {
92            CipherAlgo::Aes256 => 32,
93            CipherAlgo::TripleDes => 24,
94        }
95    }
96    pub fn iv_len(self) -> usize {
97        match self {
98            CipherAlgo::Aes256 => 16,
99            CipherAlgo::TripleDes => 8,
100        }
101    }
102    /// CBC decrypt with no padding removal (masterkey path — length is a block multiple).
103    pub fn cbc_decrypt_nopad(self, key: &[u8], iv: &[u8], ct: &[u8]) -> Option<Vec<u8>> {
104        if ct.is_empty() || ct.len() % 8 != 0 {
105            return None;
106        }
107        let mut buf = ct.to_vec();
108        match self {
109            CipherAlgo::Aes256 => {
110                let d = cbc::Decryptor::<Aes256>::new_from_slices(key, iv).ok()?;
111                d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
112            }
113            CipherAlgo::TripleDes => {
114                let d = cbc::Decryptor::<TdesEde3>::new_from_slices(key, iv).ok()?;
115                d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
116            }
117        }
118        Some(buf)
119    }
120}
121
122/// Strip PKCS#7 padding (data-blob path). Returns None on an invalid pad.
123pub fn unpad_pkcs7(data: &[u8]) -> Option<Vec<u8>> {
124    let &pad = data.last()?;
125    let pad = pad as usize;
126    if pad == 0 || pad > data.len() || pad > 16 {
127        return None;
128    }
129    if data[data.len() - pad..].iter().all(|&b| b as usize == pad) {
130        Some(data[..data.len() - pad].to_vec())
131    } else {
132        None
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    // RFC 6070 — PBKDF2-HMAC-SHA1 known-answer vectors. A genuine external oracle for the PBKDF2
141    // wiring (not a self-round-trip).
142    #[test]
143    fn pbkdf2_hmac_sha1_rfc6070() {
144        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 1, 20);
145        assert_eq!(hex(&dk), "0c60c80f961f0e71f3a9b524af6012062fe037a6");
146        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 2, 20);
147        assert_eq!(hex(&dk), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
148        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 4096, 20);
149        assert_eq!(hex(&dk), "4b007901b765489abead49d926f721d065a429c1");
150    }
151
152    // RFC 2202 — HMAC-SHA1 test case 2 (key="Jefe", data="what do ya want for nothing?").
153    #[test]
154    fn hmac_sha1_rfc2202() {
155        let mac = hmac_sha1(b"Jefe", b"what do ya want for nothing?");
156        assert_eq!(hex(&mac), "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
157    }
158
159    // RFC 4231 — HMAC-SHA512 test case 2.
160    #[test]
161    fn hmac_sha512_rfc4231() {
162        let mac = hmac_sha512(b"Jefe", b"what do ya want for nothing?");
163        assert_eq!(
164            hex(&mac),
165            "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
1669758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
167        );
168    }
169
170    #[test]
171    fn pkcs7_unpad_roundtrip() {
172        assert_eq!(unpad_pkcs7(&[b'a', b'b', 2, 2]).unwrap(), b"ab");
173        assert_eq!(unpad_pkcs7(&[1]).unwrap(), b"");
174        assert!(unpad_pkcs7(&[b'a', 2, 3]).is_none()); // inconsistent pad
175        assert!(unpad_pkcs7(&[]).is_none());
176    }
177
178    fn hex(b: &[u8]) -> String {
179        b.iter().map(|x| format!("{x:02x}")).collect()
180    }
181}