1use aes::Aes256;
6use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
7use des::TdesEde3;
8use hmac::{Hmac, Mac};
9use md4::{Digest as Md4Digest, Md4};
10use sha1::Sha1;
11use sha2::{Sha256, Sha512};
12
13pub type HmacSha1 = Hmac<Sha1>;
14pub type HmacSha512 = Hmac<Sha512>;
15
16pub fn hmac_sha1(key: &[u8], msg: &[u8]) -> [u8; 20] {
17 let mut m = <HmacSha1 as Mac>::new_from_slice(key).expect("hmac key");
18 m.update(msg);
19 m.finalize().into_bytes().into()
20}
21
22pub fn hmac_sha512(key: &[u8], msg: &[u8]) -> [u8; 64] {
23 let mut m = <HmacSha512 as Mac>::new_from_slice(key).expect("hmac key");
24 m.update(msg);
25 m.finalize().into_bytes().into()
26}
27
28pub fn md4(data: &[u8]) -> [u8; 16] {
32 let mut h = Md4::new();
33 h.update(data);
34 h.finalize().into()
35}
36
37pub fn pbkdf2_sha256(password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
40 let mut out = vec![0u8; dklen];
41 let rounds = rounds.max(1);
42 pbkdf2::pbkdf2_hmac::<Sha256>(password, salt, rounds, &mut out);
43 out
44}
45
46pub fn ms_derive_key(hash: HashAlgo, passphrase: &[u8], salt: &[u8], count: u32, dklen: usize) -> Vec<u8> {
67 let count = count.max(1);
68 let mut out = Vec::with_capacity(dklen);
69 let mut counter: u32 = 1;
70 while out.len() < dklen {
71 let mut buf = Vec::with_capacity(salt.len() + 4);
72 buf.extend_from_slice(salt);
73 buf.extend_from_slice(&counter.to_be_bytes());
74 counter += 1;
75 let mut derived = hash.hmac(passphrase, &buf);
76 for _ in 0..(count - 1) {
77 let actual = hash.hmac(passphrase, &derived);
78 for (d, a) in derived.iter_mut().zip(actual.iter()) {
79 *d ^= *a;
80 }
81 }
82 out.extend_from_slice(&derived);
83 }
84 out.truncate(dklen);
85 out
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub enum HashAlgo {
92 Sha1,
93 Sha512,
94}
95
96impl HashAlgo {
97 pub fn from_alg_id(id: u32) -> Option<Self> {
99 match id {
100 0x8004 => Some(HashAlgo::Sha1),
101 0x800e => Some(HashAlgo::Sha512),
102 _ => None,
103 }
104 }
105 pub fn digest_len(self) -> usize {
106 match self {
107 HashAlgo::Sha1 => 20,
108 HashAlgo::Sha512 => 64,
109 }
110 }
111 pub fn block_size(self) -> usize {
112 match self {
113 HashAlgo::Sha1 => 64,
114 HashAlgo::Sha512 => 128,
115 }
116 }
117 pub fn hmac(self, key: &[u8], msg: &[u8]) -> Vec<u8> {
118 match self {
119 HashAlgo::Sha1 => hmac_sha1(key, msg).to_vec(),
120 HashAlgo::Sha512 => hmac_sha512(key, msg).to_vec(),
121 }
122 }
123 pub fn pbkdf2(self, password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
125 let mut out = vec![0u8; dklen];
126 let rounds = rounds.max(1);
127 match self {
128 HashAlgo::Sha1 => pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, rounds, &mut out),
129 HashAlgo::Sha512 => pbkdf2::pbkdf2_hmac::<Sha512>(password, salt, rounds, &mut out),
130 }
131 out
132 }
133}
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub enum CipherAlgo {
138 Aes256,
139 TripleDes,
140}
141
142impl CipherAlgo {
143 pub fn from_alg_id(id: u32) -> Option<Self> {
145 match id {
146 0x6610 => Some(CipherAlgo::Aes256),
147 0x6603 => Some(CipherAlgo::TripleDes),
148 _ => None,
149 }
150 }
151 pub fn key_len(self) -> usize {
152 match self {
153 CipherAlgo::Aes256 => 32,
154 CipherAlgo::TripleDes => 24,
155 }
156 }
157 pub fn iv_len(self) -> usize {
158 match self {
159 CipherAlgo::Aes256 => 16,
160 CipherAlgo::TripleDes => 8,
161 }
162 }
163 pub fn cbc_decrypt_nopad(self, key: &[u8], iv: &[u8], ct: &[u8]) -> Option<Vec<u8>> {
165 if ct.is_empty() || ct.len() % 8 != 0 {
166 return None;
167 }
168 let mut buf = ct.to_vec();
169 match self {
170 CipherAlgo::Aes256 => {
171 let d = cbc::Decryptor::<Aes256>::new_from_slices(key, iv).ok()?;
172 d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
173 }
174 CipherAlgo::TripleDes => {
175 let d = cbc::Decryptor::<TdesEde3>::new_from_slices(key, iv).ok()?;
176 d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
177 }
178 }
179 Some(buf)
180 }
181}
182
183pub fn unpad_pkcs7(data: &[u8]) -> Option<Vec<u8>> {
185 let &pad = data.last()?;
186 let pad = pad as usize;
187 if pad == 0 || pad > data.len() || pad > 16 {
188 return None;
189 }
190 if data[data.len() - pad..].iter().all(|&b| b as usize == pad) {
191 Some(data[..data.len() - pad].to_vec())
192 } else {
193 None
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
204 fn pbkdf2_hmac_sha1_rfc6070() {
205 let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 1, 20);
206 assert_eq!(hex(&dk), "0c60c80f961f0e71f3a9b524af6012062fe037a6");
207 let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 2, 20);
208 assert_eq!(hex(&dk), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
209 let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 4096, 20);
210 assert_eq!(hex(&dk), "4b007901b765489abead49d926f721d065a429c1");
211 }
212
213 #[test]
215 fn hmac_sha1_rfc2202() {
216 let mac = hmac_sha1(b"Jefe", b"what do ya want for nothing?");
217 assert_eq!(hex(&mac), "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
218 }
219
220 #[test]
222 fn hmac_sha512_rfc4231() {
223 let mac = hmac_sha512(b"Jefe", b"what do ya want for nothing?");
224 assert_eq!(
225 hex(&mac),
226 "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
2279758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
228 );
229 }
230
231 #[test]
232 fn pkcs7_unpad_roundtrip() {
233 assert_eq!(unpad_pkcs7(&[b'a', b'b', 2, 2]).unwrap(), b"ab");
234 assert_eq!(unpad_pkcs7(&[1]).unwrap(), b"");
235 assert!(unpad_pkcs7(&[b'a', 2, 3]).is_none()); assert!(unpad_pkcs7(&[]).is_none());
237 }
238
239 fn hex(b: &[u8]) -> String {
240 b.iter().map(|x| format!("{x:02x}")).collect()
241 }
242}