Skip to main content

sheetkit_core/crypt/
standard.rs

1//! Standard Encryption (Office 2007): AES-ECB + SHA-1.
2//!
3//! This encryption method uses an AES key in ECB mode with SHA-1 for key
4//! derivation. SheetKit supports decryption only for this format.
5
6use crate::error::{Error, Result};
7use zeroize::Zeroizing;
8
9/// Parsed header from a Standard Encryption EncryptionInfo stream.
10#[derive(Debug, Clone)]
11pub struct StandardEncryptionHeader {
12    /// Encryption algorithm ID (0x6601 = AES-128).
13    pub alg_id: u32,
14    /// Hash algorithm ID (0x8004 = SHA-1).
15    pub alg_id_hash: u32,
16    /// Key size in bits (128).
17    pub key_size: u32,
18}
19
20/// Parsed verifier from a Standard Encryption EncryptionInfo stream.
21#[derive(Debug, Clone)]
22pub struct StandardEncryptionVerifier {
23    /// 16-byte salt used in key derivation.
24    pub salt: [u8; 16],
25    /// AES-ECB encrypted verifier (16 bytes).
26    pub encrypted_verifier: [u8; 16],
27    /// Size of the verifier hash (20 for SHA-1).
28    pub verifier_hash_size: u32,
29    /// AES-ECB encrypted verifier hash (32 bytes).
30    pub encrypted_verifier_hash: [u8; 32],
31}
32
33const ENCRYPTION_HEADER_FIXED_SIZE: usize = 32;
34const ENCRYPTION_VERIFIER_SIZE: usize = 72;
35const AES_BLOCK_SIZE: usize = 16;
36const CALG_SHA1: u32 = 0x0000_8004;
37const CALG_AES_128: u32 = 0x0000_660e;
38const CALG_AES_192: u32 = 0x0000_660f;
39const CALG_AES_256: u32 = 0x0000_6610;
40const PROV_RSA_AES: u32 = 24;
41
42/// Parse the Standard Encryption binary data (after the 8-byte version header).
43pub fn parse_standard_encryption_info(
44    data: &[u8],
45) -> Result<(StandardEncryptionHeader, StandardEncryptionVerifier)> {
46    if data.len() < 4 {
47        return Err(Error::Internal(
48            "Standard EncryptionInfo header too short".to_string(),
49        ));
50    }
51
52    let header_size = usize::try_from(read_u32(data, 0, "header size")?).map_err(|_| {
53        Error::Internal("Standard EncryptionInfo header size is unsupported".to_string())
54    })?;
55    if header_size < ENCRYPTION_HEADER_FIXED_SIZE {
56        return Err(Error::Internal(
57            "Standard EncryptionInfo header size is too small".to_string(),
58        ));
59    }
60    let header_end = 4usize.checked_add(header_size).ok_or_else(|| {
61        Error::Internal("Standard EncryptionInfo header size overflows".to_string())
62    })?;
63    if header_end > data.len() {
64        return Err(Error::Internal(
65            "Standard EncryptionInfo header is truncated".to_string(),
66        ));
67    }
68
69    let flags = read_u32(data, 4, "flags")?;
70    let size_extra = read_u32(data, 8, "size extra")?;
71    let alg_id = read_u32(data, 12, "algorithm ID")?;
72    let alg_id_hash = read_u32(data, 16, "hash algorithm ID")?;
73    let key_size = read_u32(data, 20, "key size")?;
74    let provider_type = read_u32(data, 24, "provider type")?;
75    let reserved1 = read_u32(data, 28, "reserved field")?;
76    let reserved2 = read_u32(data, 32, "reserved field")?;
77
78    if flags != 0x24 || size_extra != 0 || provider_type != PROV_RSA_AES {
79        return Err(Error::UnsupportedEncryption(
80            "unsupported Standard Encryption header".to_string(),
81        ));
82    }
83    if reserved1 != 0 || reserved2 != 0 {
84        return Err(Error::Internal(
85            "Standard EncryptionInfo reserved fields are not zero".to_string(),
86        ));
87    }
88    validate_standard_algorithm(alg_id, alg_id_hash, key_size)?;
89
90    let csp_name = &data[36..header_end];
91    if !csp_name.is_empty()
92        && (!csp_name.len().is_multiple_of(2) || csp_name[csp_name.len() - 2..] != [0, 0])
93    {
94        return Err(Error::Internal(
95            "Standard EncryptionInfo CSP name is malformed".to_string(),
96        ));
97    }
98
99    let header = StandardEncryptionHeader {
100        alg_id,
101        alg_id_hash,
102        key_size,
103    };
104
105    let verifier_offset = header_end;
106    let verifier_end = verifier_offset
107        .checked_add(ENCRYPTION_VERIFIER_SIZE)
108        .ok_or_else(|| {
109            Error::Internal("Standard EncryptionInfo verifier offset overflows".to_string())
110        })?;
111    if verifier_end > data.len() {
112        return Err(Error::Internal(
113            "Standard EncryptionInfo verifier too short".to_string(),
114        ));
115    }
116    let vdata = &data[verifier_offset..verifier_end];
117
118    let salt_size = read_u32(vdata, 0, "salt size")?;
119    if salt_size != 16 {
120        return Err(Error::Internal(format!(
121            "unexpected salt size: {salt_size}, expected 16"
122        )));
123    }
124
125    let mut salt = [0u8; 16];
126    salt.copy_from_slice(&vdata[4..20]);
127
128    let mut encrypted_verifier = [0u8; 16];
129    encrypted_verifier.copy_from_slice(&vdata[20..36]);
130
131    let verifier_hash_size = read_u32(vdata, 36, "verifier hash size")?;
132    if verifier_hash_size != 20 {
133        return Err(Error::Internal(format!(
134            "unexpected verifier hash size: {verifier_hash_size}, expected 20"
135        )));
136    }
137
138    let mut encrypted_verifier_hash = [0u8; 32];
139    encrypted_verifier_hash.copy_from_slice(&vdata[40..72]);
140
141    let verifier = StandardEncryptionVerifier {
142        salt,
143        encrypted_verifier,
144        verifier_hash_size,
145        encrypted_verifier_hash,
146    };
147
148    Ok((header, verifier))
149}
150
151/// Derive an AES key from a password using the Standard Encryption
152/// key derivation algorithm.
153///
154/// Algorithm:
155/// 1. H0 = SHA1(salt || password_utf16le)
156/// 2. Hi = SHA1(i_le_bytes || H_{i-1}) for i = 0..49999
157/// 3. H_final = SHA1(H || block_key_0x00000000)
158/// 4. Take first `key_size / 8` bytes, pad with 0x36 if needed
159pub fn derive_key_standard(password: &str, salt: &[u8; 16], key_size: u32) -> Vec<u8> {
160    use sha1::Digest;
161
162    let password_bytes = super::agile::utf16le_password(password);
163
164    // H0 = SHA1(salt || password)
165    let mut hasher = sha1::Sha1::new();
166    hasher.update(salt);
167    hasher.update(&*password_bytes);
168    let mut h = Zeroizing::new(hasher.finalize().to_vec());
169
170    // Hi = SHA1(i || H_{i-1}) for i = 0..49999; replaced values are wiped.
171    for i in 0u32..50_000 {
172        let mut hasher = sha1::Sha1::new();
173        hasher.update(i.to_le_bytes());
174        hasher.update(&*h);
175        h = Zeroizing::new(hasher.finalize().to_vec());
176    }
177
178    // H_final = SHA1(H || 0x00000000)
179    let mut hasher = sha1::Sha1::new();
180    hasher.update(&*h);
181    hasher.update([0u8; 4]);
182    let derived = Zeroizing::new(hasher.finalize().to_vec());
183
184    // Build cbRequiredKeyLength bytes
185    // X1 = SHA1(derived ^ 0x36 repeated to 64 bytes)
186    let key_len = (key_size / 8) as usize;
187    let mut x1_input = Zeroizing::new(vec![0x36u8; 64]);
188    for (i, byte) in derived.iter().enumerate() {
189        x1_input[i] ^= byte;
190    }
191    let mut hasher = sha1::Sha1::new();
192    hasher.update(&*x1_input);
193    let x1 = Zeroizing::new(hasher.finalize().to_vec());
194
195    // X2 = SHA1(derived ^ 0x5C repeated to 64 bytes)
196    let mut x2_input = Zeroizing::new(vec![0x5Cu8; 64]);
197    for (i, byte) in derived.iter().enumerate() {
198        x2_input[i] ^= byte;
199    }
200    let mut hasher = sha1::Sha1::new();
201    hasher.update(&*x2_input);
202    let x2 = Zeroizing::new(hasher.finalize().to_vec());
203
204    // X3 = X1 || X2
205    let mut x3 = Zeroizing::new(Vec::with_capacity(x1.len() + x2.len()));
206    x3.extend_from_slice(&x1);
207    x3.extend_from_slice(&x2);
208
209    x3[..key_len].to_vec()
210}
211
212/// Verify a password against Standard Encryption verifier data.
213/// Returns the derived key on success.
214pub fn verify_password_standard(
215    password: &str,
216    header: &StandardEncryptionHeader,
217    verifier: &StandardEncryptionVerifier,
218) -> Result<Vec<u8>> {
219    validate_standard_algorithm(header.alg_id, header.alg_id_hash, header.key_size)?;
220    let key = Zeroizing::new(derive_key_standard(
221        password,
222        &verifier.salt,
223        header.key_size,
224    ));
225
226    // AES-ECB decrypt the encrypted verifier
227    let decrypted_verifier = Zeroizing::new(aes_ecb_decrypt(&key, &verifier.encrypted_verifier)?);
228
229    // Compute SHA-1 hash of decrypted verifier
230    use sha1::Digest;
231    let mut hasher = sha1::Sha1::new();
232    hasher.update(&*decrypted_verifier);
233    let expected_hash = Zeroizing::new(hasher.finalize().to_vec());
234
235    // AES-ECB decrypt the encrypted verifier hash
236    let decrypted_hash = Zeroizing::new(aes_ecb_decrypt(&key, &verifier.encrypted_verifier_hash)?);
237
238    // Compare first `verifier_hash_size` bytes
239    let hash_size = verifier.verifier_hash_size as usize;
240    if expected_hash.len() < hash_size || decrypted_hash.len() < hash_size {
241        return Err(Error::IncorrectPassword);
242    }
243    use subtle::ConstantTimeEq;
244    if !bool::from(expected_hash[..hash_size].ct_eq(&decrypted_hash[..hash_size])) {
245        return Err(Error::IncorrectPassword);
246    }
247
248    Ok(key.to_vec())
249}
250
251/// Decrypt the EncryptedPackage using Standard Encryption (AES-ECB).
252pub fn decrypt_package_standard(encrypted_data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
253    if encrypted_data.len() < 8 {
254        return Err(Error::Internal(
255            "EncryptedPackage too short for size prefix".to_string(),
256        ));
257    }
258
259    let original_size_u64 =
260        u64::from_le_bytes(encrypted_data[..8].try_into().map_err(|_| {
261            Error::Internal("EncryptedPackage size prefix is malformed".to_string())
262        })?);
263    let original_size = usize::try_from(original_size_u64).map_err(|_| {
264        Error::Internal("EncryptedPackage original size is unsupported".to_string())
265    })?;
266    let ciphertext = &encrypted_data[8..];
267    if !ciphertext.len().is_multiple_of(AES_BLOCK_SIZE) {
268        return Err(Error::Internal(
269            "EncryptedPackage ciphertext is not AES block aligned".to_string(),
270        ));
271    }
272
273    let decrypted = aes_ecb_decrypt(key, ciphertext)?;
274    if original_size > decrypted.len() {
275        return Err(Error::Internal(
276            "EncryptedPackage original size exceeds decrypted data".to_string(),
277        ));
278    }
279
280    Ok(decrypted[..original_size].to_vec())
281}
282
283/// AES-ECB decryption helper.
284fn aes_ecb_decrypt(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
285    use aes::cipher::generic_array::GenericArray;
286    use aes::cipher::{BlockDecrypt, KeyInit};
287    if !data.len().is_multiple_of(AES_BLOCK_SIZE) {
288        return Err(Error::Internal(
289            "AES ciphertext is not block aligned".to_string(),
290        ));
291    }
292
293    fn decrypt<C: BlockDecrypt + KeyInit>(key: &[u8], data: &[u8]) -> Vec<u8> {
294        let cipher = C::new(GenericArray::from_slice(key));
295        let mut result = Vec::with_capacity(data.len());
296        for chunk in data.as_chunks::<AES_BLOCK_SIZE>().0 {
297            let mut block = GenericArray::clone_from_slice(chunk);
298            cipher.decrypt_block(&mut block);
299            result.extend_from_slice(&block);
300        }
301        result
302    }
303
304    match key.len() {
305        16 => Ok(decrypt::<aes::Aes128>(key, data)),
306        24 => Ok(decrypt::<aes::Aes192>(key, data)),
307        32 => Ok(decrypt::<aes::Aes256>(key, data)),
308        len => Err(Error::UnsupportedEncryption(format!(
309            "unsupported Standard Encryption AES key size: {len} bytes"
310        ))),
311    }
312}
313
314fn read_u32(data: &[u8], offset: usize, field: &str) -> Result<u32> {
315    let bytes = data
316        .get(offset..offset + 4)
317        .ok_or_else(|| Error::Internal(format!("Standard EncryptionInfo {field} is truncated")))?;
318    Ok(u32::from_le_bytes(bytes.try_into().map_err(|_| {
319        Error::Internal(format!("Standard EncryptionInfo {field} is malformed"))
320    })?))
321}
322
323fn validate_standard_algorithm(alg_id: u32, alg_id_hash: u32, key_size: u32) -> Result<()> {
324    if alg_id_hash != CALG_SHA1 {
325        return Err(Error::UnsupportedEncryption(format!(
326            "unsupported Standard Encryption hash algorithm: {alg_id_hash:#x}"
327        )));
328    }
329    let expected_key_size = match alg_id {
330        CALG_AES_128 => 128,
331        CALG_AES_192 => 192,
332        CALG_AES_256 => 256,
333        _ => {
334            return Err(Error::UnsupportedEncryption(format!(
335                "unsupported Standard Encryption algorithm: {alg_id:#x}"
336            )));
337        }
338    };
339    if key_size != expected_key_size {
340        return Err(Error::UnsupportedEncryption(format!(
341            "unsupported Standard Encryption key size: {key_size}"
342        )));
343    }
344    Ok(())
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    fn valid_standard_info() -> Vec<u8> {
352        let header_size = ENCRYPTION_HEADER_FIXED_SIZE + 2;
353        let mut data = vec![0u8; 4 + header_size + ENCRYPTION_VERIFIER_SIZE];
354        data[0..4].copy_from_slice(&(header_size as u32).to_le_bytes());
355        data[4..8].copy_from_slice(&0x24u32.to_le_bytes());
356        data[12..16].copy_from_slice(&CALG_AES_128.to_le_bytes());
357        data[16..20].copy_from_slice(&CALG_SHA1.to_le_bytes());
358        data[20..24].copy_from_slice(&128u32.to_le_bytes());
359        data[24..28].copy_from_slice(&PROV_RSA_AES.to_le_bytes());
360        data[36..38].copy_from_slice(&[0, 0]);
361
362        let verifier = 4 + header_size;
363        data[verifier..verifier + 4].copy_from_slice(&16u32.to_le_bytes());
364        data[verifier + 4..verifier + 20].copy_from_slice(&[7; 16]);
365        data[verifier + 36..verifier + 40].copy_from_slice(&20u32.to_le_bytes());
366        data
367    }
368
369    fn aes_ecb_encrypt_for_test(key: &[u8; 16], data: &[u8]) -> Vec<u8> {
370        use aes::cipher::generic_array::GenericArray;
371        use aes::cipher::{BlockEncrypt, KeyInit};
372
373        let cipher = aes::Aes128::new(GenericArray::from_slice(key));
374        let mut encrypted = Vec::with_capacity(data.len());
375        for chunk in data.as_chunks::<AES_BLOCK_SIZE>().0 {
376            let mut block = GenericArray::clone_from_slice(chunk);
377            cipher.encrypt_block(&mut block);
378            encrypted.extend_from_slice(&block);
379        }
380        encrypted
381    }
382
383    #[test]
384    fn test_parse_standard_encryption_info_too_short() {
385        let data = vec![0u8; 10];
386        assert!(parse_standard_encryption_info(&data).is_err());
387    }
388
389    #[test]
390    fn test_parse_standard_encryption_info_reads_unshifted_algorithm_fields() {
391        let data = valid_standard_info();
392        let (header, verifier) = parse_standard_encryption_info(&data).unwrap();
393
394        assert_eq!(header.alg_id, CALG_AES_128);
395        assert_eq!(header.alg_id_hash, CALG_SHA1);
396        assert_eq!(header.key_size, 128);
397        assert_eq!(verifier.salt, [7; 16]);
398    }
399
400    #[test]
401    fn test_parse_standard_encryption_info_rejects_invalid_header_size() {
402        let mut too_small = valid_standard_info();
403        too_small[0..4].copy_from_slice(&31u32.to_le_bytes());
404        assert!(parse_standard_encryption_info(&too_small).is_err());
405
406        let mut oversized = valid_standard_info();
407        oversized[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
408        assert!(parse_standard_encryption_info(&oversized).is_err());
409    }
410
411    #[test]
412    fn test_parse_standard_encryption_info_rejects_truncated_verifier() {
413        let mut data = valid_standard_info();
414        data.truncate(data.len() - 1);
415        assert!(parse_standard_encryption_info(&data).is_err());
416    }
417
418    #[test]
419    fn test_parse_standard_encryption_info_rejects_invalid_verifier_sizes() {
420        let mut invalid_salt = valid_standard_info();
421        let verifier = 4 + ENCRYPTION_HEADER_FIXED_SIZE + 2;
422        invalid_salt[verifier..verifier + 4].copy_from_slice(&15u32.to_le_bytes());
423        assert!(parse_standard_encryption_info(&invalid_salt).is_err());
424
425        let mut invalid_hash = valid_standard_info();
426        invalid_hash[verifier + 36..verifier + 40].copy_from_slice(&19u32.to_le_bytes());
427        assert!(parse_standard_encryption_info(&invalid_hash).is_err());
428    }
429
430    #[test]
431    fn test_parse_standard_encryption_info_rejects_unsupported_algorithm() {
432        let mut data = valid_standard_info();
433        data[12..16].copy_from_slice(&0x6601u32.to_le_bytes());
434        assert!(parse_standard_encryption_info(&data).is_err());
435    }
436
437    #[test]
438    fn test_verify_password_standard_accepts_valid_verifier() {
439        use sha1::Digest;
440
441        let mut data = valid_standard_info();
442        let verifier_offset = 4 + ENCRYPTION_HEADER_FIXED_SIZE + 2;
443        let salt = [7; 16];
444        let key: [u8; 16] = derive_key_standard("password", &salt, 128)
445            .try_into()
446            .unwrap();
447        let verifier_plaintext = [9; AES_BLOCK_SIZE];
448        let encrypted_verifier = aes_ecb_encrypt_for_test(&key, &verifier_plaintext);
449        data[verifier_offset + 20..verifier_offset + 36].copy_from_slice(&encrypted_verifier);
450
451        let mut hash_plaintext = [0u8; 32];
452        hash_plaintext[..20].copy_from_slice(&sha1::Sha1::digest(verifier_plaintext));
453        let encrypted_hash = aes_ecb_encrypt_for_test(&key, &hash_plaintext);
454        data[verifier_offset + 40..verifier_offset + 72].copy_from_slice(&encrypted_hash);
455
456        let (header, verifier) = parse_standard_encryption_info(&data).unwrap();
457        assert_eq!(
458            verify_password_standard("password", &header, &verifier).unwrap(),
459            key
460        );
461        assert!(verify_password_standard("incorrect", &header, &verifier).is_err());
462    }
463
464    #[test]
465    fn test_derive_key_standard_produces_correct_length() {
466        let salt = [0u8; 16];
467        let key = derive_key_standard("password", &salt, 128);
468        assert_eq!(key.len(), 16);
469    }
470
471    #[test]
472    fn test_derive_key_standard_different_passwords() {
473        let salt = [1u8; 16];
474        let key1 = derive_key_standard("password1", &salt, 128);
475        let key2 = derive_key_standard("password2", &salt, 128);
476        assert_ne!(key1, key2);
477    }
478
479    #[test]
480    fn test_derive_key_standard_deterministic() {
481        let salt = [42u8; 16];
482        let key1 = derive_key_standard("test", &salt, 128);
483        let key2 = derive_key_standard("test", &salt, 128);
484        assert_eq!(key1, key2);
485    }
486
487    #[test]
488    fn test_decrypt_package_standard_rejects_malformed_ciphertext() {
489        let mut encrypted = 1u64.to_le_bytes().to_vec();
490        encrypted.extend_from_slice(&[0; 15]);
491        assert!(decrypt_package_standard(&encrypted, &[0; 16]).is_err());
492    }
493
494    #[test]
495    fn test_decrypt_package_standard_rejects_size_beyond_plaintext() {
496        let mut encrypted = 17u64.to_le_bytes().to_vec();
497        encrypted.extend_from_slice(&[0; AES_BLOCK_SIZE]);
498        assert!(decrypt_package_standard(&encrypted, &[0; 16]).is_err());
499    }
500
501    #[test]
502    fn test_decrypt_package_standard_rejects_unsupported_key_size() {
503        let mut encrypted = 0u64.to_le_bytes().to_vec();
504        encrypted.extend_from_slice(&[0; AES_BLOCK_SIZE]);
505        assert!(decrypt_package_standard(&encrypted, &[0; 15]).is_err());
506    }
507}