use crate::coordinate::Range;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PasswordHash {
Legacy(String),
Iso {
algorithm: String,
hash: String,
salt: String,
spin_count: u32,
},
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct PasswordAttrs {
pub legacy: &'static str,
pub algorithm: &'static str,
pub hash: &'static str,
pub salt: &'static str,
pub spin_count: &'static str,
}
impl PasswordAttrs {
pub(crate) const PLAIN: Self = Self {
legacy: "password",
algorithm: "algorithmName",
hash: "hashValue",
salt: "saltValue",
spin_count: "spinCount",
};
pub(crate) const WORKBOOK: Self = Self {
legacy: "workbookPassword",
algorithm: "workbookAlgorithmName",
hash: "workbookHashValue",
salt: "workbookSaltValue",
spin_count: "workbookSpinCount",
};
pub(crate) const REVISIONS: Self = Self {
legacy: "revisionsPassword",
algorithm: "revisionsAlgorithmName",
hash: "revisionsHashValue",
salt: "revisionsSaltValue",
spin_count: "revisionsSpinCount",
};
}
impl PasswordHash {
pub const DEFAULT_SPIN_COUNT: u32 = 10_000;
pub const EXCEL_SPIN_COUNT: u32 = 100_000;
#[must_use]
pub fn new(password: &str) -> Option<Self> {
let mut salt = [0u8; 16];
getrandom::fill(&mut salt).ok()?;
Some(Self::iso(password, &salt, Self::EXCEL_SPIN_COUNT))
}
#[must_use]
pub fn iso(password: &str, salt: &[u8], spin_count: u32) -> Self {
Self::Iso {
algorithm: "SHA-512".to_owned(),
hash: base64(&spin::<sha2::Sha512>(password, salt, spin_count)),
salt: base64(salt),
spin_count,
}
}
#[must_use]
pub fn legacy(password: &str) -> Self {
Self::Legacy(format!("{:04X}", legacy_verifier(password)))
}
#[must_use]
pub fn verify(&self, password: &str) -> bool {
match self {
Self::Legacy(verifier) => {
u16::from_str_radix(verifier, 16).is_ok_and(|v| v == legacy_verifier(password))
}
Self::Iso {
algorithm,
hash,
salt,
spin_count,
} => {
let Some(salt) = unbase64(salt) else {
return false;
};
let got = match algorithm.to_ascii_uppercase().as_str() {
"SHA-512" => spin::<sha2::Sha512>(password, &salt, *spin_count),
"SHA-384" => spin::<sha2::Sha384>(password, &salt, *spin_count),
"SHA-256" => spin::<sha2::Sha256>(password, &salt, *spin_count),
"SHA-1" => spin::<sha1::Sha1>(password, &salt, *spin_count),
_ => return false,
};
base64(&got) == *hash
}
}
}
pub(crate) fn from_attrs(
attrs: PasswordAttrs,
lookup: impl Fn(&str) -> Option<String>,
) -> Option<Self> {
let algorithm = lookup(attrs.algorithm).filter(|v| !v.is_empty());
if let Some(algorithm) = algorithm {
return Some(Self::Iso {
algorithm,
hash: lookup(attrs.hash).unwrap_or_default(),
salt: lookup(attrs.salt).unwrap_or_default(),
spin_count: lookup(attrs.spin_count)
.and_then(|v| v.parse().ok())
.unwrap_or(Self::DEFAULT_SPIN_COUNT),
});
}
lookup(attrs.legacy)
.filter(|v| !v.is_empty())
.map(Self::Legacy)
}
#[cfg(feature = "write")]
pub(crate) fn to_attrs(&self, attrs: PasswordAttrs) -> Vec<(&'static str, String)> {
match self {
Self::Legacy(verifier) => vec![(attrs.legacy, verifier.clone())],
Self::Iso {
algorithm,
hash,
salt,
spin_count,
} => vec![
(attrs.algorithm, algorithm.clone()),
(attrs.hash, hash.clone()),
(attrs.salt, salt.clone()),
(attrs.spin_count, spin_count.to_string()),
],
}
}
}
fn spin<D: sha2::Digest>(password: &str, salt: &[u8], spin_count: u32) -> Vec<u8> {
let mut first = D::new();
first.update(salt);
for unit in password.encode_utf16() {
first.update(unit.to_le_bytes());
}
let mut hash = first.finalize().to_vec();
for i in 0..spin_count {
let mut next = D::new();
next.update(&hash);
next.update(i.to_le_bytes());
hash = next.finalize().to_vec();
}
hash
}
fn legacy_verifier(password: &str) -> u16 {
let bytes: Vec<u16> = password.encode_utf16().map(|u| u & 0xFF).collect();
let mut hash: u16 = 0;
for &byte in bytes.iter().rev() {
hash = ((hash >> 14) & 1) | ((hash << 1) & 0x7FFF);
hash ^= byte;
}
hash = ((hash >> 14) & 1) | ((hash << 1) & 0x7FFF);
#[expect(
clippy::cast_possible_truncation,
reason = "the old method hashes the length modulo 2^16"
)]
let length = bytes.len() as u16;
hash ^ length ^ 0xCE4B
}
const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn base64(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |n, (i, &b)| n | (u32::from(b) << (16 - 8 * i)));
for i in 0..4 {
if i <= chunk.len() {
out.push(char::from(BASE64[(n >> (18 - 6 * i) & 63) as usize]));
} else {
out.push('=');
}
}
}
out
}
pub(crate) fn unbase64(text: &str) -> Option<Vec<u8>> {
let text = text.trim_end_matches('=');
let mut out = Vec::with_capacity(text.len() * 3 / 4);
let (mut n, mut bits) = (0u32, 0);
for c in text.bytes() {
let digit = BASE64.iter().position(|&d| d == c)?;
n = (n << 6) | u32::try_from(digit).ok()?;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push(u8::try_from((n >> bits) & 0xFF).ok()?);
}
}
Some(out)
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SheetProtection {
pub sheet: Option<bool>,
pub objects: Option<bool>,
pub scenarios: Option<bool>,
pub format_cells: Option<bool>,
pub format_columns: Option<bool>,
pub format_rows: Option<bool>,
pub insert_columns: Option<bool>,
pub insert_rows: Option<bool>,
pub insert_hyperlinks: Option<bool>,
pub delete_columns: Option<bool>,
pub delete_rows: Option<bool>,
pub sort: Option<bool>,
pub auto_filter: Option<bool>,
pub pivot_tables: Option<bool>,
pub select_locked_cells: Option<bool>,
pub select_unlocked_cells: Option<bool>,
pub password: Option<PasswordHash>,
}
impl SheetProtection {
#[must_use]
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
#[must_use]
#[cfg(feature = "write")]
pub(crate) fn flags(&self) -> [(&'static str, Option<bool>); 16] {
[
("sheet", self.sheet),
("objects", self.objects),
("scenarios", self.scenarios),
("formatCells", self.format_cells),
("formatColumns", self.format_columns),
("formatRows", self.format_rows),
("insertColumns", self.insert_columns),
("insertRows", self.insert_rows),
("insertHyperlinks", self.insert_hyperlinks),
("deleteColumns", self.delete_columns),
("deleteRows", self.delete_rows),
("sort", self.sort),
("autoFilter", self.auto_filter),
("pivotTables", self.pivot_tables),
("selectLockedCells", self.select_locked_cells),
("selectUnlockedCells", self.select_unlocked_cells),
]
}
pub(crate) fn slots(&mut self) -> [(&'static str, &mut Option<bool>); 16] {
[
("sheet", &mut self.sheet),
("objects", &mut self.objects),
("scenarios", &mut self.scenarios),
("formatCells", &mut self.format_cells),
("formatColumns", &mut self.format_columns),
("formatRows", &mut self.format_rows),
("insertColumns", &mut self.insert_columns),
("insertRows", &mut self.insert_rows),
("insertHyperlinks", &mut self.insert_hyperlinks),
("deleteColumns", &mut self.delete_columns),
("deleteRows", &mut self.delete_rows),
("sort", &mut self.sort),
("autoFilter", &mut self.auto_filter),
("pivotTables", &mut self.pivot_tables),
("selectLockedCells", &mut self.select_locked_cells),
("selectUnlockedCells", &mut self.select_unlocked_cells),
]
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ProtectedRange {
pub name: String,
pub sqref: Vec<Range>,
pub password: Option<PasswordHash>,
pub security_descriptor: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WorkbookProtection {
pub lock_revision: Option<bool>,
pub lock_structure: Option<bool>,
pub lock_windows: Option<bool>,
pub workbook_password: Option<PasswordHash>,
pub revisions_password: Option<PasswordHash>,
}
impl WorkbookProtection {
#[must_use]
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
#[must_use]
#[cfg(feature = "write")]
pub(crate) fn locks(&self) -> [(&'static str, Option<bool>); 3] {
[
("lockRevision", self.lock_revision),
("lockStructure", self.lock_structure),
("lockWindows", self.lock_windows),
]
}
pub(crate) fn lock_slots(&mut self) -> [(&'static str, &mut Option<bool>); 3] {
[
("lockRevision", &mut self.lock_revision),
("lockStructure", &mut self.lock_structure),
("lockWindows", &mut self.lock_windows),
]
}
}
#[cfg(test)]
mod tests {
use super::{PasswordAttrs, PasswordHash, SheetProtection, base64, unbase64};
fn lookup(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
let owned: Vec<(String, String)> = pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect();
move |name| {
owned
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.clone())
}
}
#[test]
fn an_algorithm_name_selects_the_iso_form() {
let attrs = [
("algorithmName", "SHA-512"),
("hashValue", "aGFzaA=="),
("saltValue", "c2FsdA=="),
("spinCount", "100000"),
("password", "CC1A"),
];
assert_eq!(
PasswordHash::from_attrs(PasswordAttrs::PLAIN, lookup(&attrs)),
Some(PasswordHash::Iso {
algorithm: "SHA-512".into(),
hash: "aGFzaA==".into(),
salt: "c2FsdA==".into(),
spin_count: 100_000,
})
);
}
#[test]
fn a_missing_spin_count_falls_back_to_the_default() {
let attrs = [("algorithmName", "SHA-512"), ("hashValue", "aGFzaA==")];
assert_eq!(
PasswordHash::from_attrs(PasswordAttrs::PLAIN, lookup(&attrs)),
Some(PasswordHash::Iso {
algorithm: "SHA-512".into(),
hash: "aGFzaA==".into(),
salt: String::new(),
spin_count: PasswordHash::DEFAULT_SPIN_COUNT,
})
);
}
#[test]
fn without_an_algorithm_the_legacy_verifier_is_the_password() {
let attrs = [("password", "CC1A")];
assert_eq!(
PasswordHash::from_attrs(PasswordAttrs::PLAIN, lookup(&attrs)),
Some(PasswordHash::Legacy("CC1A".into()))
);
assert_eq!(
PasswordHash::from_attrs(PasswordAttrs::PLAIN, lookup(&[])),
None
);
assert_eq!(
PasswordHash::from_attrs(PasswordAttrs::PLAIN, lookup(&[("password", "")])),
None
);
}
#[test]
fn the_workbook_spells_its_two_passwords_apart() {
let attrs = [
("workbookPassword", "CC1A"),
("revisionsAlgorithmName", "SHA-1"),
("revisionsHashValue", "aA=="),
];
assert_eq!(
PasswordHash::from_attrs(PasswordAttrs::WORKBOOK, lookup(&attrs)),
Some(PasswordHash::Legacy("CC1A".into()))
);
assert!(matches!(
PasswordHash::from_attrs(PasswordAttrs::REVISIONS, lookup(&attrs)),
Some(PasswordHash::Iso { .. })
));
}
#[test]
#[cfg(feature = "write")]
fn the_flag_tables_agree_on_names_and_order() {
let mut protection = SheetProtection::default();
let names: Vec<&str> = protection.flags().iter().map(|(n, _)| *n).collect();
let slots: Vec<&str> = protection.slots().iter().map(|(n, _)| *n).collect();
assert_eq!(names, slots);
}
#[test]
fn base64_round_trips() {
for bytes in [&b""[..], b"f", b"fo", b"foo", b"foob", b"\xff\x00\x10"] {
assert_eq!(unbase64(&base64(bytes)).as_deref(), Some(bytes));
}
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
assert_eq!(base64(b"fo"), "Zm8=");
}
#[test]
fn a_hash_verifies_its_own_password_only() {
let hash = PasswordHash::iso("secret", b"0123456789abcdef", 1000);
assert!(hash.verify("secret"));
assert!(!hash.verify("Secret"));
let hash = PasswordHash::legacy("secret");
assert!(hash.verify("secret"));
assert!(!hash.verify("other"));
}
}