sheetkit_core/
protection.rs1#[derive(Debug, Clone, Default)]
5pub struct WorkbookProtectionConfig {
6 pub password: Option<String>,
8 pub lock_structure: bool,
10 pub lock_windows: bool,
12 pub lock_revision: bool,
14}
15
16pub fn legacy_password_hash(password: &str) -> u16 {
26 if password.is_empty() {
27 return 0;
28 }
29 let mut hash: u16 = 0;
30 let bytes = password.as_bytes();
31 for (i, &byte) in bytes.iter().enumerate() {
32 let rotation = (i + 1) % 15;
33 let value = byte as u16;
34 let rotated = ((value << rotation) & 0x7FFF) | (value >> (15 - rotation));
35 hash ^= rotated & 0x7FFF;
36 }
37 hash ^= bytes.len() as u16;
38 hash ^= 0xCE4B;
39 hash
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn test_legacy_password_hash_empty() {
48 assert_eq!(legacy_password_hash(""), 0);
49 }
50
51 #[test]
52 fn test_legacy_password_hash_office_compatible_vectors() {
53 assert_eq!(legacy_password_hash("a"), 0xCE88);
54 assert_eq!(legacy_password_hash("test"), 0xCBEB);
55 assert_eq!(legacy_password_hash("password"), 0x83AF);
56 assert_eq!(legacy_password_hash("VelvetSweatshop"), 0x9A0A);
57 }
58
59 #[test]
60 fn test_legacy_password_hash_rotates_within_15_bits() {
61 assert_eq!(legacy_password_hash("abcdefghij"), 0xFEF1);
62 assert_eq!(legacy_password_hash("abcdefghijklmno"), 0xC6BC);
63 assert_eq!(legacy_password_hash("abcdefghijklmnop"), 0xC643);
64 }
65
66 #[test]
67 fn test_legacy_password_hash_format() {
68 let h = legacy_password_hash("password");
70 let hex = format!("{:04X}", h);
71 assert_eq!(hex.len(), 4);
72 }
73
74 #[test]
75 fn test_workbook_protection_config_default() {
76 let config = WorkbookProtectionConfig::default();
77 assert!(config.password.is_none());
78 assert!(!config.lock_structure);
79 assert!(!config.lock_windows);
80 assert!(!config.lock_revision);
81 }
82}