Skip to main content

msoffice_crypto/
hash.rs

1//! Everything this crate computes with the hash algorithm a file names.
2//!
3//! An agile file names *two* hashes and they drive disjoint halves of the algorithm:
4//! `keyData/@hashAlgorithm` governs the per-segment package IVs, the two `dataIntegrity`
5//! IVs and the package HMAC, while `p:encryptedKey/@hashAlgorithm` governs the spin hash,
6//! the block-key derivation and the password verifier.
7//!
8//! [MS-OFFCRYPTO] §2.3.4.10 tells a *writer* to make them equal — the
9//! `PasswordKeyEncryptor`'s "hashing algorithm specified MUST be the same as the hashing
10//! algorithm specified for the Encryption.keyData element" — and Office obliges, which is
11//! what hides a crossed-element bug in any round trip against your own writer (herumi
12//! `include/encode.hpp:146-147` sets both from one pair). A *reader* is handed bytes, not
13//! a promise: a file whose two elements disagree is non-conforming and still has to
14//! decrypt under the hash each half was actually written with, because assuming they
15//! match means silently using the wrong one on whichever half was guessed. The two
16//! callers therefore pass their own algorithm in; nothing here decides which is in force,
17//! and nothing here refuses the disagreement.
18//!
19//! Sources for the derivations: herumi/msoffice (BSD-3)
20//! `include/crypto_util.hpp:432-452`, `include/decode.hpp:88-101`; msoffcrypto-tool (MIT)
21//! `msoffcrypto/method/ecma376_agile.py:169-201`. Behaviour cross-checked against
22//! LibreOffice `oox/source/crypto/AgileEngine.cxx:194-232, 252-262` (MPL-2.0, read-only —
23//! no expression from it is reproduced here).
24//!
25//! **Why this is its own module.** The four operations below used to be private to
26//! `integrity`, whose one-sentence purpose is verifying the `dataIntegrity` HMAC. Once
27//! the password path needed the same dispatch (issue #11), leaving them there would have
28//! given that module a second job and forced `agile` to import its hashing from the
29//! integrity checker. The enum itself stays in `classify`, which must *report* the hash
30//! in a build with no cipher crate at all; this module is the `crypto-ops` half.
31
32use crate::error::Error;
33use crate::file_params::Invariant;
34use hmac::{Hmac, KeyInit, Mac};
35use sha1::Sha1;
36use sha2::{Digest, Sha256, Sha384, Sha512};
37
38/// The hash named by `keyData/@hashAlgorithm` or `p:encryptedKey/@hashAlgorithm`.
39///
40/// Declared in `classify` — the detection build has to *report* it, and a second copy
41/// here would be a second spelling table to keep in step. Re-exported rather than
42/// re-declared so every module keeps one import path.
43pub(crate) use crate::classify::HashAlgorithm;
44
45impl HashAlgorithm {
46    /// The unhyphenated ECMA-376 spelling — what Office writes, and what this crate
47    /// prints in errors. `HashAlgorithm::parse` also accepts the hyphenated form
48    /// (`SHA-1`), so a file that used it is reported back in the canonical spelling
49    /// rather than in its own.
50    ///
51    /// `pub` rather than `pub(crate)` for the same reason as [`Self::digest_len`]: the
52    /// spelling is the one a caller has to put back into `hashAlgorithm` when it
53    /// describes its own parameters, and it is not derivable from `Debug`, which prints
54    /// the Rust variant name (`Sha512`) and not the attribute value (`SHA512`).
55    pub fn name(self) -> &'static str {
56        match self {
57            Self::Sha1 => "SHA1",
58            Self::Sha256 => "SHA256",
59            Self::Sha384 => "SHA384",
60            Self::Sha512 => "SHA512",
61        }
62    }
63
64    /// Digest length in bytes. A `hashSize` attribute is checked against this before it
65    /// is trusted as a truncation length, and `keyBits / 8` before it is trusted as one.
66    ///
67    /// **Why this is `pub` when everything else on this impl is internal.** It is a fact
68    /// about SHA, not about this crate — FIPS 180-4 fixes all four numbers, and no
69    /// decision of ours can move them. What is ours is the *coupling* it feeds: a caller
70    /// choosing encryption parameters meets a refusal when `keyBits / 8` exceeds the
71    /// digest of the hash it named (`can_carry_key_bits`, internal), and without this
72    /// number it cannot reason about that rule before it trips over it — it would have
73    /// to hardcode the same four constants to predict our own error. `hashSize` is not
74    /// a companion to this: [MS-OFFCRYPTO] §2.3.4.10 requires it to *equal* the named
75    /// hash's digest length, so it is derived from this value rather than chosen beside
76    /// it, which is why no setter for it exists.
77    pub fn digest_len(self) -> usize {
78        match self {
79            Self::Sha1 => 20,
80            Self::Sha256 => 32,
81            Self::Sha384 => 48,
82            Self::Sha512 => 64,
83        }
84    }
85
86    /// Can a block key of `key_bits` bits be cut from this hash's digest without padding
87    /// it?
88    ///
89    /// The one predicate behind three refusals, so that they cannot drift: the
90    /// `keyBits`/`hashAlgorithm` pair check in `agile::parse_encryption_info`, the
91    /// re-check inside `agile::derive_block_key` (which is reachable from three call
92    /// sites and declines to trust the parser), and the message
93    /// `agile::unusable_key_bits` builds for both. The expression was written out twice
94    /// before this function existed, and two copies of a bound are one bound and one
95    /// latent divergence.
96    ///
97    /// The bound is *not* in [MS-OFFCRYPTO]. §2.3.4.11 ends by telling an implementation
98    /// to 0x36-pad a digest shorter than `PasswordKeyEncryptor.keyBits` and to truncate
99    /// a longer one, and `ST_KeyBits` has a minimum of 8 and a multiple-of-8 constraint
100    /// but **no maximum at all**, so the combination is legal on the wire. This crate
101    /// refuses the padding half deliberately — see `agile::derive_block_key` for the
102    /// argument and for what the four references each do instead. This predicate is
103    /// therefore a house rule with a spec-shaped name, and says so rather than implying
104    /// the spec forbids what it rejects.
105    ///
106    /// The truncating divide is the right one and not a rounding hazard. Every value
107    /// that reaches here has passed `agile::check_key_bits`, whose allowlist holds only
108    /// multiples of 8, so `key_bits / 8` is exact today; and were a non-multiple ever to
109    /// arrive, `key_bits / 8` is *the same expression* the truncation downstream uses to
110    /// cut the digest, so the predicate stays a true statement about that cut rather
111    /// than an independent calculation that could disagree with it.
112    pub(crate) fn can_carry_key_bits(self, key_bits: u32) -> bool {
113        (key_bits / 8) as usize <= self.digest_len()
114    }
115
116    /// `H(data)`.
117    ///
118    /// One operand, used by the password verifier over the *whole* decrypted
119    /// `encryptedVerifierHashInput` (herumi `include/decode.hpp:97-98`).
120    pub(crate) fn digest(self, data: &[u8]) -> Vec<u8> {
121        self.digest_two(data, &[])
122    }
123
124    /// `H(first || second)` — order matters, and reversing the two is a silently-wrong
125    /// key or IV rather than an error (herumi `include/crypto_util.hpp:438` for the IV, `:449` for the key of the same shape).
126    ///
127    /// Every hash this format performs has this shape, which is why it takes two slices
128    /// rather than an 8-byte block key: the two `dataIntegrity` IVs and the three block
129    /// keys append an 8-byte constant, the package IVs a 4-byte little-endian segment
130    /// index, the spin hash's first round the UTF-16LE password and its later rounds the
131    /// previous digest (the spin hash through [`Self::digest_two_into`], since rc.5).
132    pub(crate) fn digest_two(self, first: &[u8], second: &[u8]) -> Vec<u8> {
133        macro_rules! run {
134            ($d:ty) => {{
135                let mut h = <$d>::new();
136                h.update(first);
137                h.update(second);
138                h.finalize().to_vec()
139            }};
140        }
141        match self {
142            Self::Sha1 => run!(Sha1),
143            Self::Sha256 => run!(Sha256),
144            Self::Sha384 => run!(Sha384),
145            Self::Sha512 => run!(Sha512),
146        }
147    }
148
149    /// `H(first || second)`, truncated to `out.len()` and written into `out` — the same
150    /// bytes [`Self::digest_two`] returns, without the `Vec`.
151    ///
152    /// **Why the truncating form is the one that takes a slot.** Its caller,
153    /// `agile::derive_block_key`, wants `key_len` bytes of a digest that is longer, and
154    /// the shortest way to say that in Rust builds the whole digest on the heap and then
155    /// copies a prefix out of it — two allocations, one of them holding the complete
156    /// digest of `H_final`, both freed without being wiped. Writing into a
157    /// `Dynamic::new_with` slot makes the wrapper the only place the bytes ever land.
158    /// See `docs/design/heap-residue.md` for why the abandoned block is beyond the
159    /// wrapper's reach.
160    ///
161    /// **`digest_two` is not reimplemented in terms of this, deliberately.** Its
162    /// remaining callers want an owned digest of the natural length, and routing that
163    /// through a slot they would then have to allocate anyway buys nothing. The two
164    /// share the format's `H(a || b)` and nothing else, and a test below pins them to
165    /// the same bytes.
166    ///
167    /// `spin_hash` was one of those callers until rc.5 and is now this function's
168    /// second: its loop, which runs `spinCount` — up to 10 000 000 — times per decrypt,
169    /// alternates between two wrapped slots of exactly `digest_len` bytes, so there the
170    /// slot is not allocated per call at all, and every round lands somewhere wiped.
171    ///
172    /// # Contract
173    ///
174    /// `out.len()` must not exceed [`Self::digest_len`]. It is the caller's check, not
175    /// this function's, because the caller is the one with an [`Error`] to return and a
176    /// message worth reading: `derive_block_key` asks [`Self::can_carry_key_bits`] two
177    /// lines earlier and refuses with `agile::unusable_key_bits`. A longer `out` is
178    /// filled as far as the digest goes and its tail left as the caller supplied it —
179    /// which from `Dynamic::new_with` is zero — rather than padded with `0x36` the way
180    /// [`fit_iv`] pads an IV. Neither is defensible as a *key*; the refusal upstream is,
181    /// and that is why there is one.
182    pub(crate) fn digest_two_into(self, first: &[u8], second: &[u8], out: &mut [u8]) {
183        // The contract above, made loud where it is stated. Without this, violating it
184        // is *silent*: `out` keeps whatever tail the caller allocated, which from
185        // `Dynamic::new_with` is zeros, and a short digest becomes a zero-padded key
186        // rather than an error — precisely what `derive_block_key` refuses to do one
187        // frame up, arrived at by omission instead of by decision.
188        //
189        // `debug_assert` rather than a `Result`: the caller already owns the refusal and
190        // its message, so returning a second error here would duplicate the decision
191        // without improving it. This catches a wrong call in every test run and compiles
192        // out of release, so it adds no panic to a shipped parse path.
193        debug_assert!(
194            out.len() <= self.digest_len(),
195            "digest_two_into: out is {} bytes, {} produces {} — the caller must refuse \
196             this before asking (see can_carry_key_bits)",
197            out.len(),
198            self.name(),
199            self.digest_len(),
200        );
201        macro_rules! run {
202            ($d:ty) => {{
203                let mut h = <$d>::new();
204                h.update(first);
205                h.update(second);
206                let digest = h.finalize();
207                let n = out.len().min(digest.len());
208                out[..n].copy_from_slice(&digest[..n]);
209            }};
210        }
211        match self {
212            Self::Sha1 => run!(Sha1),
213            Self::Sha256 => run!(Sha256),
214            Self::Sha384 => run!(Sha384),
215            Self::Sha512 => run!(Sha512),
216        }
217    }
218
219    #[cfg(test)]
220    pub(crate) fn hmac(self, key: &[u8], message: &[u8]) -> Vec<u8> {
221        let mut mac = self.hmac_state(key);
222        mac.update(message);
223        mac.finalize()
224    }
225
226    /// An HMAC under this hash, fed a piece at a time: the shape the streaming paths need,
227    /// where the `EncryptedPackage` stream passes through once and is never whole in
228    /// memory. [`hmac`](Self::hmac) is this with the whole message in one `update`, so
229    /// the two cannot disagree.
230    pub(crate) fn hmac_state(self, key: &[u8]) -> HmacState {
231        macro_rules! run {
232            ($d:ty, $variant:ident) => {
233                // HMAC accepts a key of any length, so `new_from_slice` cannot fail
234                // here; the `expect` documents that rather than hiding a real case.
235                HmacState::$variant(
236                    <Hmac<$d>>::new_from_slice(key).expect("HMAC accepts keys of any length"),
237                )
238            };
239        }
240        match self {
241            Self::Sha1 => run!(Sha1, Sha1),
242            Self::Sha256 => run!(Sha256, Sha256),
243            Self::Sha384 => run!(Sha384, Sha384),
244            Self::Sha512 => run!(Sha512, Sha512),
245        }
246    }
247}
248
249/// An HMAC in progress, under whichever hash the file named.
250///
251/// **Holds ipad/opad state derived from the key, wiped on drop.** `hmac`'s `zeroize`
252/// feature, on since 0.1.0-rc.12 (it was not available on `hmac` 0.12), wipes the inner and
253/// outer hash cores when this drops, as it does for the one-shot [`HashAlgorithm::hmac`].
254/// The streaming paths keep this alive for a whole pass over the package rather than for
255/// one call, which lengthens the window in which the state exists: the capability to forge
256/// a tag under that one key.
257/// It lives on the stack of the function running the pass and is never boxed or cloned.
258pub(crate) enum HmacState {
259    Sha1(Hmac<Sha1>),
260    Sha256(Hmac<Sha256>),
261    Sha384(Hmac<Sha384>),
262    Sha512(Hmac<Sha512>),
263}
264
265impl HmacState {
266    pub(crate) fn update(&mut self, data: &[u8]) {
267        match self {
268            Self::Sha1(m) => m.update(data),
269            Self::Sha256(m) => m.update(data),
270            Self::Sha384(m) => m.update(data),
271            Self::Sha512(m) => m.update(data),
272        }
273    }
274
275    /// The tag, as an owned `Vec` of exactly the digest's length — the shape
276    /// `IntegrityTag::new` takes by move, so nothing is abandoned on the way in.
277    pub(crate) fn finalize(self) -> Vec<u8> {
278        match self {
279            Self::Sha1(m) => m.finalize().into_bytes().to_vec(),
280            Self::Sha256(m) => m.finalize().into_bytes().to_vec(),
281            Self::Sha384(m) => m.finalize().into_bytes().to_vec(),
282            Self::Sha512(m) => m.finalize().into_bytes().to_vec(),
283        }
284    }
285}
286
287/// `H(keyData.saltValue || suffix)` truncated to `keyData/@blockSize`.
288///
289/// Every IV in the agile format that is seeded by `<keyData>` comes from this one
290/// derivation, and both of its consumers live outside this module: the two
291/// `dataIntegrity` blob IVs (suffix = an 8-byte block key) and [`crate::segments`]'s
292/// per-segment package IVs (suffix = the little-endian segment index), which both the
293/// agile decrypt and encrypt paths run through since plan D4. They are the same shape and
294/// take their hash from the same file attribute, so they share the function rather than
295/// each spelling it out — a package IV that hardcoded SHA-512 while the integrity path
296/// honoured the file is precisely how a mixed-algorithm document could be reported
297/// `Verified` and then decrypted with the wrong IVs.
298///
299/// Truncation only. herumi's shared `normalizeKey` would 0x36-pad a digest shorter than
300/// `block_size` (`include/crypto_util.hpp:38-41`), but every supported hash produces at
301/// least 20 bytes and `block_size` is pinned to 16 by both callers, so that branch is
302/// unreachable here — and a file that reached it would be one we should reject rather
303/// than pad.
304pub(crate) fn derive_iv(
305    hash: HashAlgorithm,
306    salt: &[u8],
307    suffix: &[u8],
308    block_size: usize,
309) -> Result<Vec<u8>, Error> {
310    let digest = hash.digest_two(salt, suffix);
311    // The parser pins blockSize to 16, under every digest's length (#47).
312    if digest.len() < block_size {
313        return Err(Error::InvariantViolated(Invariant::BlockSizeOverDigest));
314    }
315    Ok(fit_iv(&digest, block_size))
316}
317
318/// [MS-OFFCRYPTO] §2.3.4.12 last step: an IV shorter than `blockSize` is padded with
319/// `0x36`; a longer one is truncated.
320///
321/// Package and `dataIntegrity` IVs go through [`derive_iv`] first, whose digest is
322/// always longer than the AES block, so they only ever truncate. The password-encryptor
323/// blobs use the salt itself as the IV ("if a blockKey is not provided", same section),
324/// and `saltSize` is 1..=65 536 — a short salt used to fail inside AES as a 16-byte-IV
325/// mismatch rather than being padded the way the spec writes.
326pub(crate) fn fit_iv(bytes: &[u8], block_size: usize) -> Vec<u8> {
327    if bytes.len() >= block_size {
328        bytes[..block_size].to_vec()
329    } else {
330        let mut iv = Vec::with_capacity(block_size);
331        iv.extend_from_slice(bytes);
332        iv.resize(block_size, 0x36);
333        iv
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    /// An HMAC fed a piece at a time is the HMAC of the whole message, under every hash
342    /// and at every chunk size the streaming paths can produce: one byte (a reader that
343    /// returns short), 15 (never block-aligned), 4096 (a whole segment) and 4097 (a
344    /// segment and one byte over). The one-shot expectation is computed straight from the
345    /// `hmac` crate, not from [`HashAlgorithm::hmac`], which is now this same state fed
346    /// once and would agree with it whatever it did.
347    #[test]
348    fn a_chunked_hmac_is_the_one_shot_hmac() {
349        let key: Vec<u8> = (0..64u8).collect();
350        let message: Vec<u8> = (0..20_000u32).map(|i| (i % 253) as u8).collect();
351        for hash in [
352            HashAlgorithm::Sha1,
353            HashAlgorithm::Sha256,
354            HashAlgorithm::Sha384,
355            HashAlgorithm::Sha512,
356        ] {
357            macro_rules! one_shot {
358                ($d:ty) => {{
359                    let mut m = <Hmac<$d>>::new_from_slice(&key).unwrap();
360                    m.update(&message);
361                    m.finalize().into_bytes().to_vec()
362                }};
363            }
364            let want = match hash {
365                HashAlgorithm::Sha1 => one_shot!(Sha1),
366                HashAlgorithm::Sha256 => one_shot!(Sha256),
367                HashAlgorithm::Sha384 => one_shot!(Sha384),
368                HashAlgorithm::Sha512 => one_shot!(Sha512),
369            };
370            assert_eq!(want.len(), hash.digest_len());
371            for chunk in [1usize, 15, 4096, 4097] {
372                let mut mac = hash.hmac_state(&key);
373                for piece in message.chunks(chunk) {
374                    mac.update(piece);
375                }
376                assert_eq!(mac.finalize(), want, "{hash:?} fed in {chunk}-byte pieces");
377            }
378            assert_eq!(hash.hmac(&key, &message), want, "{hash:?} one-shot");
379        }
380    }
381
382    /// Each variant must actually run the algorithm it names. A `match` arm that fell
383    /// through to the wrong hasher would be invisible to every other test in the crate
384    /// as long as writer and reader agreed on it — which, this crate being both, they
385    /// would.
386    #[test]
387    fn each_variant_runs_the_algorithm_it_names() {
388        // Known-answer vectors for the empty string, from FIPS 180-4.
389        for (hash, want) in [
390            (
391                HashAlgorithm::Sha1,
392                "da39a3ee5e6b4b0d3255bfef95601890afd80709",
393            ),
394            (
395                HashAlgorithm::Sha256,
396                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
397            ),
398            (
399                HashAlgorithm::Sha384,
400                "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da\
401                 274edebfe76f65fbd51ad2f14898b95b",
402            ),
403            (
404                HashAlgorithm::Sha512,
405                "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce\
406                 47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
407            ),
408        ] {
409            let got: String = hash
410                .digest(b"")
411                .iter()
412                .map(|b| format!("{b:02x}"))
413                .collect();
414            assert_eq!(got, want.replace(' ', ""), "{hash:?}");
415            assert_eq!(hash.digest_len(), got.len() / 2);
416        }
417    }
418
419    /// `digest` is `digest_two` with an empty tail, and the split must not change the
420    /// bytes: the verifier hashes one operand, every other site hashes two.
421    #[test]
422    fn digest_is_digest_two_with_nothing_appended() {
423        for hash in [
424            HashAlgorithm::Sha1,
425            HashAlgorithm::Sha256,
426            HashAlgorithm::Sha384,
427            HashAlgorithm::Sha512,
428        ] {
429            assert_eq!(hash.digest(b"abc"), hash.digest_two(b"a", b"bc"));
430            assert_ne!(hash.digest_two(b"a", b"bc"), hash.digest_two(b"bc", b"a"));
431        }
432    }
433
434    /// `digest_two_into` must be `digest_two` truncated and nothing else.
435    ///
436    /// Two functions computing the same format step is exactly the drift the crate
437    /// avoids elsewhere by sharing one expression, and here it cannot: one returns an
438    /// owned `Vec` and the other writes a slot, which is the whole point of having both.
439    /// So the agreement is pinned by test instead — at *every* truncation length, not
440    /// only at the four `keyBits / 8` values in the wild, because a `copy_from_slice`
441    /// with the wrong endpoint is a silently wrong key rather than an error.
442    #[test]
443    fn digest_two_into_is_digest_two_truncated() {
444        for hash in [
445            HashAlgorithm::Sha1,
446            HashAlgorithm::Sha256,
447            HashAlgorithm::Sha384,
448            HashAlgorithm::Sha512,
449        ] {
450            let want = hash.digest_two(b"H_final stand-in", b"\x14\x6e\x0b\xe7\xab\xac\xd0\xd6");
451            assert_eq!(want.len(), hash.digest_len());
452            for n in 0..=hash.digest_len() {
453                let mut got = vec![0xAAu8; n];
454                hash.digest_two_into(
455                    b"H_final stand-in",
456                    b"\x14\x6e\x0b\xe7\xab\xac\xd0\xd6",
457                    &mut got,
458                );
459                assert_eq!(got, want[..n], "{hash:?} truncated to {n}");
460            }
461        }
462    }
463
464    /// Asking for more bytes than the digest has is a **contract violation**, not a
465    /// behaviour.
466    ///
467    /// This replaced a test that pinned what the over-long case *does* — fill as far as
468    /// the digest goes, leave the caller's tail, which from `Dynamic::new_with` is zeros.
469    /// That was written to stop someone "improving" it into a `0x36` pad, which is a real
470    /// hazard and the right thing to want. But pinning the behaviour of a call the
471    /// contract forbids documents it as available, and the behaviour it documented is a
472    /// silently zero-padded key — exactly what `agile::derive_block_key` refuses to
473    /// produce one frame up, reached here by omission rather than by decision.
474    ///
475    /// So the `debug_assert` in `digest_two_into` is the guard and this is its proof. The
476    /// `0x36` hazard is covered better than before: a pad of *any* byte is now
477    /// unreachable, rather than merely a different constant from the one nobody wants.
478    ///
479    /// `cfg(debug_assertions)` because that is when the assert exists — it compiles out
480    /// of release so a shipped parse path gains no panic, which means a release test run
481    /// would see the old silent behaviour and this `should_panic` would fail.
482    #[test]
483    #[should_panic(expected = "the caller must refuse this before asking")]
484    #[cfg(debug_assertions)]
485    fn digest_two_into_refuses_more_bytes_than_the_digest_holds() {
486        let mut over = vec![0u8; HashAlgorithm::Sha1.digest_len() + 1];
487        HashAlgorithm::Sha1.digest_two_into(b"H_final stand-in", b"block-key", &mut over);
488    }
489
490    /// [MS-OFFCRYPTO] §2.3.4.12 step 3, both directions: short pads with `0x36`, long
491    /// truncates, exact is left alone.
492    ///
493    /// The pad byte is `0x36` and not zero. A zero pad is the same length and the same
494    /// shape, decrypts to rubbish, and — on a file with no `<dataIntegrity>` element —
495    /// produces no error at all, so the constant is the whole content of this test.
496    #[test]
497    fn fit_iv_pads_short_with_0x36_and_truncates_long() {
498        // Short: eight salt bytes then eight pad bytes.
499        let mut want = vec![0x11u8; 8];
500        want.resize(16, 0x36);
501        assert_eq!(fit_iv(&[0x11u8; 8], 16), want);
502
503        // Long: the first blockSize bytes, nothing appended.
504        assert_eq!(fit_iv(&[0x22u8; 32], 16), vec![0x22u8; 16]);
505
506        // Exact: identity, which is every file Office writes.
507        assert_eq!(fit_iv(&[0x33u8; 16], 16), vec![0x33u8; 16]);
508
509        // A single byte is still a whole IV, and every byte after the first is the pad.
510        assert_eq!(
511            fit_iv(&[0x44u8], 16),
512            [&[0x44u8][..], &[0x36u8; 15][..]].concat()
513        );
514    }
515
516    /// `derive_iv` truncates and never reaches [`fit_iv`]'s pad branch: every hash this
517    /// crate accepts produces at least 20 bytes and `blockSize` is pinned to 16, so a
518    /// `blockSize` past the digest is refused above rather than padded. Stated as a test
519    /// so that wiring `fit_iv` into the salt-as-IV path cannot quietly turn this one into
520    /// a pad as well — the two cases are the same spec sentence and different code.
521    #[test]
522    fn derive_iv_truncates_and_refuses_rather_than_padding() {
523        for hash in [
524            HashAlgorithm::Sha1,
525            HashAlgorithm::Sha256,
526            HashAlgorithm::Sha384,
527            HashAlgorithm::Sha512,
528        ] {
529            let iv = derive_iv(hash, b"salt", b"\x00\x00\x00\x00", 16).expect("16 <= 20");
530            assert_eq!(iv, hash.digest_two(b"salt", b"\x00\x00\x00\x00")[..16]);
531            // One byte past the digest is an error, not a 0x36 tail.
532            let err = derive_iv(hash, b"salt", b"", hash.digest_len() + 1)
533                .expect_err("blockSize past the digest must be refused");
534            assert!(matches!(
535                err,
536                Error::InvariantViolated(crate::Invariant::BlockSizeOverDigest)
537            ));
538        }
539    }
540}