Skip to main content

hide_object/
lib.rs

1use std::io::{self, Read, Write};
2
3use hide_crypto::{
4    ChunkCipher, ContentKey, CryptoError, DerivedKey, RecipientPublic, RecipientSecret,
5};
6pub use hide_format::Metadata;
7use hide_format::{
8    CHUNK_LEN, FormatError, MAX_RECIPIENTS, PREAMBLE_LEN, Preamble, ProtectedHeader,
9    RecipientStanza, SUITE, SignatureStanza, TAG_LEN,
10};
11use hide_sign::{SigningIdentity, VerifyingIdentity};
12use thiserror::Error;
13use zeroize::Zeroizing;
14
15const DATA: u8 = 1;
16const FINAL: u8 = 2;
17const MAX_CHUNKS: u64 = 1 << 32;
18/// A signed encrypt must hold the whole plaintext to hash it, so it is the one
19/// path that cannot stream. Unsigned encryption has no such limit.
20pub const MAX_SIGNED_INPUT: u64 = 1 << 30;
21const RECORD_LEN: usize = CHUNK_LEN + TAG_LEN;
22const CHUNK_AAD_LEN: usize = 91;
23const SIGNING_CONTEXT: &[u8] = b"HIDE/0.5 container";
24
25#[derive(Debug, Error)]
26pub enum ObjectError {
27    #[error(transparent)]
28    Format(#[from] FormatError),
29    #[error(transparent)]
30    Crypto(#[from] CryptoError),
31    #[error("I/O operation failed: {0}")]
32    Io(#[from] io::Error),
33    #[error("no matching recipient or invalid header authentication")]
34    NoMatchingRecipient,
35    #[error("truncated payload")]
36    TruncatedPayload,
37    #[error("invalid payload record")]
38    InvalidRecord,
39    #[error("unexpected bytes after final record")]
40    TrailingData,
41    #[error("object exceeds the chunk limit")]
42    ObjectTooLarge,
43    #[error("recipient count must be between 1 and 64")]
44    InvalidRecipients,
45    #[error("signature does not verify")]
46    InvalidSignature,
47    #[error("container is signed but the reader was not asked to verify")]
48    UnexpectedSignature,
49    #[error("container is not signed")]
50    MissingSignature,
51}
52
53/// Where a signature is written. Public signatures are readable by anyone
54/// holding the file; confidential ones only by those who can already decrypt.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum SignaturePlacement {
57    /// In the unencrypted header. Reveals the signer to anyone with the file.
58    Public,
59    /// Inside the encrypted metadata. Hides the signer from non-recipients.
60    Confidential,
61    /// Signs, then discards the signature while leaving the preamble claiming
62    /// minor 2. Exists only so tests can reach the stripped-signature check.
63    #[cfg(feature = "test-vectors")]
64    #[doc(hidden)]
65    Stripped,
66}
67
68#[derive(Debug, PartialEq, Eq)]
69pub struct VerifiedObject {
70    pub metadata: Metadata,
71    pub plaintext_len: u64,
72    /// The signer, if the container carried a signature that verified.
73    pub signer: Option<VerifyingIdentity>,
74}
75
76struct ObjectMaterial {
77    cek: ContentKey,
78    object_id: [u8; 32],
79    payload_salt: [u8; 16],
80}
81
82pub fn encrypt<R: Read, W: Write>(
83    input: &mut R,
84    output: &mut W,
85    recipients: &[RecipientPublic],
86    metadata: &Metadata,
87) -> Result<u64, ObjectError> {
88    validate_recipients(recipients)?;
89    let material = ObjectMaterial {
90        cek: ContentKey::generate()?,
91        object_id: hide_crypto::random_array()?,
92        payload_salt: hide_crypto::random_array()?,
93    };
94    let stanzas = recipients
95        .iter()
96        .map(|recipient| {
97            hide_crypto::wrap_cek(recipient, &material.cek, &material.object_id).map(|wrapped| {
98                RecipientStanza {
99                    encapsulation: wrapped.encapsulation,
100                    wrapped_cek: wrapped.wrapped_cek,
101                }
102            })
103        })
104        .collect::<Result<Vec<_>, _>>()?;
105    encrypt_with_material(input, output, metadata, material, stanzas)
106}
107
108fn validate_recipients(recipients: &[RecipientPublic]) -> Result<(), ObjectError> {
109    if recipients.is_empty() || recipients.len() > MAX_RECIPIENTS {
110        return Err(ObjectError::InvalidRecipients);
111    }
112    Ok(())
113}
114
115/// Encrypts and signs. Unlike [`encrypt`], this buffers the payload, because the
116/// signature commits to the plaintext and so cannot be produced while streaming.
117pub fn encrypt_signed<R: Read, W: Write>(
118    input: &mut R,
119    output: &mut W,
120    recipients: &[RecipientPublic],
121    metadata: &Metadata,
122    identity: &SigningIdentity,
123    placement: SignaturePlacement,
124) -> Result<u64, ObjectError> {
125    validate_recipients(recipients)?;
126    let material = ObjectMaterial {
127        cek: ContentKey::generate()?,
128        object_id: hide_crypto::random_array()?,
129        payload_salt: hide_crypto::random_array()?,
130    };
131    let stanzas = recipients
132        .iter()
133        .map(|recipient| {
134            hide_crypto::wrap_cek(recipient, &material.cek, &material.object_id).map(|wrapped| {
135                RecipientStanza {
136                    encapsulation: wrapped.encapsulation,
137                    wrapped_cek: wrapped.wrapped_cek,
138                }
139            })
140        })
141        .collect::<Result<Vec<_>, _>>()?;
142    encrypt_inner(
143        input,
144        output,
145        metadata,
146        material,
147        stanzas,
148        Some((identity, placement)),
149    )
150}
151
152fn encrypt_with_material<R: Read, W: Write>(
153    input: &mut R,
154    output: &mut W,
155    metadata: &Metadata,
156    material: ObjectMaterial,
157    recipients: Vec<RecipientStanza>,
158) -> Result<u64, ObjectError> {
159    encrypt_inner(input, output, metadata, material, recipients, None)
160}
161
162/// Commits to the recipient set, the metadata and the plaintext. Binding only
163/// the header would let any recipient re-encrypt different content under the
164/// same header and keep the signature valid, since they hold the CEK and the
165/// payload salt is public.
166///
167/// The metadata is bound as its *plaintext* signing base rather than via the
168/// header's ciphertext: sealing is randomised and the confidential placement
169/// reseals after signing, so the ciphertext a verifier sees is not the one that
170/// existed when the signature was made.
171fn transcript(
172    object_id: &[u8; 32],
173    recipients: &[RecipientStanza],
174    metadata_base: &[u8],
175    plaintext_hash: &[u8; 32],
176    plaintext_len: u64,
177) -> Vec<u8> {
178    let mut message = Vec::new();
179    message.extend_from_slice(b"HIDE/0.5 transcript");
180    message.extend_from_slice(&SUITE.to_be_bytes());
181    message.extend_from_slice(object_id);
182    message.extend_from_slice(&(recipients.len() as u64).to_be_bytes());
183    for stanza in recipients {
184        message.extend_from_slice(&stanza.encapsulation);
185        message.extend_from_slice(&stanza.wrapped_cek);
186    }
187    message.extend_from_slice(&(metadata_base.len() as u64).to_be_bytes());
188    message.extend_from_slice(metadata_base);
189    message.extend_from_slice(plaintext_hash);
190    message.extend_from_slice(&plaintext_len.to_be_bytes());
191    message
192}
193
194fn encrypt_inner<R: Read, W: Write>(
195    input: &mut R,
196    output: &mut W,
197    metadata: &Metadata,
198    material: ObjectMaterial,
199    recipients: Vec<RecipientStanza>,
200    signer: Option<(&SigningIdentity, SignaturePlacement)>,
201) -> Result<u64, ObjectError> {
202    // Signing needs the plaintext hash, which is only known once the payload has
203    // been consumed, so the container is built in memory and written at the end.
204    // Bounded, because a signed encrypt is the one path that cannot stream.
205    let mut plaintext = Zeroizing::new(Vec::new());
206    let (metadata, plaintext_hash, plaintext_len) = match signer {
207        None => (metadata.clone(), None, None),
208        Some(_) => {
209            input
210                .take(MAX_SIGNED_INPUT + 1)
211                .read_to_end(&mut plaintext)?;
212            if plaintext.len() as u64 > MAX_SIGNED_INPUT {
213                return Err(ObjectError::ObjectTooLarge);
214            }
215            let hash = hide_crypto::hash(&[&plaintext]);
216            (metadata.clone(), Some(hash), Some(plaintext.len() as u64))
217        }
218    };
219
220    let metadata_key =
221        hide_crypto::derive_key(&material.cek, &material.object_id, b"HIDE/0.1 metadata")?;
222
223    // The signing base is the metadata without any signature; both placements
224    // commit to it. It is only hashed into the transcript, never sealed on its
225    // own: the metadata key and its fixed nonce must encrypt exactly one thing.
226    let base_metadata = Zeroizing::new(metadata.signing_base()?);
227    let mut header = ProtectedHeader {
228        object_id: material.object_id,
229        recipients,
230        encrypted_metadata: Vec::new(),
231        signatures: Vec::new(),
232    };
233
234    let mut metadata = metadata;
235    if let Some((identity, placement)) = signer {
236        let message = transcript(
237            &material.object_id,
238            &header.recipients,
239            &base_metadata,
240            &plaintext_hash.expect("set when signing"),
241            plaintext_len.expect("set when signing"),
242        );
243        let stanza = SignatureStanza {
244            verifying_key: identity.verifying_key().to_bytes().to_vec(),
245            signature: identity.sign(SIGNING_CONTEXT, &message).to_vec(),
246        };
247        match placement {
248            SignaturePlacement::Public => header.signatures.push(stanza),
249            SignaturePlacement::Confidential => metadata.signature = Some(stanza),
250            #[cfg(feature = "test-vectors")]
251            SignaturePlacement::Stripped => drop(stanza),
252        }
253    }
254
255    // Exactly one seal under the metadata key, whichever placement was chosen.
256    let final_metadata = Zeroizing::new(metadata.encode()?);
257    header.encrypted_metadata = hide_crypto::seal(
258        &metadata_key,
259        &[0; 12],
260        &metadata_aad(&material.object_id),
261        &final_metadata,
262    )?;
263
264    let signed = signer.is_some();
265    let protected = header.encode()?;
266    let header_length = hide_format::encode_header(&protected, &[0; 32])?.len();
267    let preamble = Preamble::with_signed(header_length, signed)?.encode();
268    let mac_key =
269        hide_crypto::derive_key(&material.cek, &material.object_id, b"HIDE/0.1 header-mac")?;
270    let mac = hide_crypto::mac(&mac_key, &[&preamble, &protected])?;
271    output.write_all(&preamble)?;
272    output.write_all(&hide_format::encode_header(&protected, &mac)?)?;
273    output.write_all(&material.payload_salt)?;
274    let key = payload_key(&material.cek, &material.object_id, &material.payload_salt)?;
275    let header_hash = hide_crypto::hash(&[&protected]);
276    if signed {
277        encrypt_records(
278            &mut plaintext.as_slice(),
279            output,
280            &key,
281            &material.object_id,
282            &header_hash,
283        )
284    } else {
285        encrypt_records(input, output, &key, &material.object_id, &header_hash)
286    }
287}
288
289/// Writes provisional plaintext. The writer must be private staging storage, not a
290/// published file or stdout. Commit it only after this function returns Ok.
291/// Integrity does not authenticate the sender or verify a human identity.
292pub fn decrypt_to_staging<R: Read, W: Write>(
293    input: &mut R,
294    staging: &mut W,
295    secret: &RecipientSecret,
296) -> Result<VerifiedObject, ObjectError> {
297    let mut preamble_bytes = [0; PREAMBLE_LEN];
298    input.read_exact(&mut preamble_bytes)?;
299    let preamble = Preamble::decode(&preamble_bytes)?;
300    let mut header_bytes = vec![0; preamble.header_len()];
301    input.read_exact(&mut header_bytes)?;
302    let (protected, mac) = hide_format::decode_header(&header_bytes)?;
303    let header = ProtectedHeader::decode(&protected)?;
304    let cek = recover_cek(secret, &header, &preamble_bytes, &protected, &mac)?;
305    let metadata_key = hide_crypto::derive_key(&cek, &header.object_id, b"HIDE/0.1 metadata")?;
306    let metadata_plaintext = hide_crypto::open(
307        &metadata_key,
308        &[0; 12],
309        &metadata_aad(&header.object_id),
310        &header.encrypted_metadata,
311    )?;
312    let metadata = Metadata::decode(&metadata_plaintext)?;
313    let mut salt = [0; 16];
314    read_payload(input, &mut salt)?;
315    let key = payload_key(&cek, &header.object_id, &salt)?;
316
317    // The signature commits to the plaintext, so it can only be checked once the
318    // payload has been read. Hash it on the way past rather than buffering.
319    let mut hasher = PlaintextHasher::new(staging);
320    let plaintext_len = decrypt_records(
321        input,
322        &mut hasher,
323        &key,
324        &header.object_id,
325        &hide_crypto::hash(&[&protected]),
326    )?;
327    let plaintext_hash = hasher.finish();
328
329    let signer = verify_signature(
330        &header,
331        &metadata,
332        preamble.is_signed(),
333        &plaintext_hash,
334        plaintext_len,
335    )?;
336    Ok(VerifiedObject {
337        metadata,
338        plaintext_len,
339        signer,
340    })
341}
342
343/// Returns the signer when the container carries a signature that verifies, and
344/// refuses the object otherwise. Called before the caller may publish plaintext.
345fn verify_signature(
346    header: &ProtectedHeader,
347    metadata: &Metadata,
348    preamble_says_signed: bool,
349    plaintext_hash: &[u8; 32],
350    plaintext_len: u64,
351) -> Result<Option<VerifyingIdentity>, ObjectError> {
352    let stanza = match (header.signatures.first(), metadata.signature.as_ref()) {
353        (Some(_), Some(_)) => return Err(ObjectError::InvalidSignature),
354        (Some(stanza), None) | (None, Some(stanza)) => stanza,
355        (None, None) => {
356            // A preamble claiming minor 2 with no signature is a stripped
357            // signature, not an unsigned object.
358            return if preamble_says_signed {
359                Err(ObjectError::MissingSignature)
360            } else {
361                Ok(None)
362            };
363        }
364    };
365    if !preamble_says_signed {
366        return Err(ObjectError::UnexpectedSignature);
367    }
368
369    let identity = VerifyingIdentity::from_bytes(&stanza.verifying_key)
370        .map_err(|_| ObjectError::InvalidSignature)?;
371    let message = transcript(
372        &header.object_id,
373        &header.recipients,
374        &metadata.signing_base()?,
375        plaintext_hash,
376        plaintext_len,
377    );
378    identity
379        .verify(SIGNING_CONTEXT, &message, &stanza.signature)
380        .map_err(|_| ObjectError::InvalidSignature)?;
381    Ok(Some(identity))
382}
383
384fn recover_cek(
385    secret: &RecipientSecret,
386    header: &ProtectedHeader,
387    preamble: &[u8],
388    protected: &[u8],
389    mac: &[u8; 32],
390) -> Result<ContentKey, ObjectError> {
391    for stanza in &header.recipients {
392        if let Ok(cek) = hide_crypto::unwrap_cek(
393            secret,
394            &header.object_id,
395            &stanza.encapsulation,
396            &stanza.wrapped_cek,
397        ) {
398            let key = hide_crypto::derive_key(&cek, &header.object_id, b"HIDE/0.1 header-mac")?;
399            if hide_crypto::verify_mac(&key, &[preamble, protected], mac).is_ok() {
400                return Ok(cek);
401            }
402        }
403    }
404    Err(ObjectError::NoMatchingRecipient)
405}
406
407/// Hashes plaintext as it streams to staging, so verifying a signature over the
408/// content does not require buffering the whole object.
409struct PlaintextHasher<'a, W: Write> {
410    inner: &'a mut W,
411    hasher: hide_crypto::Hasher,
412}
413
414impl<'a, W: Write> PlaintextHasher<'a, W> {
415    fn new(inner: &'a mut W) -> Self {
416        Self {
417            inner,
418            hasher: hide_crypto::Hasher::new(),
419        }
420    }
421
422    fn finish(self) -> [u8; 32] {
423        self.hasher.finish()
424    }
425}
426
427impl<W: Write> Write for PlaintextHasher<'_, W> {
428    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
429        let written = self.inner.write(buffer)?;
430        self.hasher.update(&buffer[..written]);
431        Ok(written)
432    }
433
434    fn flush(&mut self) -> io::Result<()> {
435        self.inner.flush()
436    }
437}
438
439fn metadata_aad(object_id: &[u8; 32]) -> Vec<u8> {
440    [
441        b"HIDE/0.1 metadata".as_slice(),
442        object_id,
443        &SUITE.to_be_bytes(),
444    ]
445    .concat()
446}
447
448fn payload_key(
449    cek: &ContentKey,
450    object_id: &[u8; 32],
451    salt: &[u8; 16],
452) -> Result<DerivedKey, CryptoError> {
453    hide_crypto::derive_key(
454        cek,
455        salt,
456        &[b"HIDE/0.1 payload".as_slice(), object_id].concat(),
457    )
458}
459
460fn nonce(counter: u64, kind: u8) -> [u8; 12] {
461    let mut nonce = [0; 12];
462    nonce[3..11].copy_from_slice(&counter.to_be_bytes());
463    nonce[11] = u8::from(kind == FINAL);
464    nonce
465}
466
467fn chunk_aad(
468    object_id: &[u8; 32],
469    header_hash: &[u8; 32],
470    counter: u64,
471    kind: u8,
472    length: usize,
473) -> [u8; CHUNK_AAD_LEN] {
474    let mut aad = [0; CHUNK_AAD_LEN];
475    aad[..14].copy_from_slice(b"HIDE/0.1 chunk");
476    aad[14..46].copy_from_slice(object_id);
477    aad[46..78].copy_from_slice(header_hash);
478    aad[78..86].copy_from_slice(&counter.to_be_bytes());
479    aad[86] = kind;
480    aad[87..].copy_from_slice(&(length as u32).to_be_bytes());
481    aad
482}
483
484fn read_chunk<R: Read>(reader: &mut R, buffer: &mut [u8]) -> Result<usize, io::Error> {
485    let mut length = 0;
486    while length < buffer.len() {
487        match reader.read(&mut buffer[length..]) {
488            Ok(0) => break,
489            Ok(count) => length += count,
490            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
491            Err(error) => return Err(error),
492        }
493    }
494    Ok(length)
495}
496
497fn encrypt_records<R: Read, W: Write>(
498    input: &mut R,
499    output: &mut W,
500    key: &DerivedKey,
501    object_id: &[u8; 32],
502    header_hash: &[u8; 32],
503) -> Result<u64, ObjectError> {
504    let cipher = ChunkCipher::new(key)?;
505    let mut current = Zeroizing::new(vec![0; RECORD_LEN]);
506    let mut next = Zeroizing::new(vec![0; RECORD_LEN]);
507    let mut length = read_chunk(input, &mut current[..CHUNK_LEN])?;
508    let mut counter = 0;
509    let mut total = 0;
510    loop {
511        if counter >= MAX_CHUNKS {
512            return Err(ObjectError::ObjectTooLarge);
513        }
514        let next_length = read_chunk(input, &mut next[..CHUNK_LEN])?;
515        let kind = if next_length == 0 { FINAL } else { DATA };
516        let aad = chunk_aad(object_id, header_hash, counter, kind, length);
517        let sealed = cipher.seal_in_place(&nonce(counter, kind), &aad, &mut current, length)?;
518        let mut record = [0; 5];
519        record[0] = kind;
520        record[1..].copy_from_slice(&(sealed as u32).to_be_bytes());
521        output.write_all(&record)?;
522        output.write_all(&current[..sealed])?;
523        total += length as u64;
524        if kind == FINAL {
525            return Ok(total);
526        }
527        core::mem::swap(&mut current, &mut next);
528        length = next_length;
529        counter += 1;
530    }
531}
532
533fn decrypt_records<R: Read, W: Write>(
534    input: &mut R,
535    staging: &mut W,
536    key: &DerivedKey,
537    object_id: &[u8; 32],
538    header_hash: &[u8; 32],
539) -> Result<u64, ObjectError> {
540    let cipher = ChunkCipher::new(key)?;
541    let mut buffer = Zeroizing::new(vec![0; RECORD_LEN]);
542    let mut total = 0;
543    for counter in 0..MAX_CHUNKS {
544        let mut record = [0; 5];
545        read_payload(input, &mut record)?;
546        let kind = record[0];
547        let ciphertext_len =
548            u32::from_be_bytes([record[1], record[2], record[3], record[4]]) as usize;
549        let length = record_length(kind, ciphertext_len, counter)?;
550        let ciphertext = &mut buffer[..ciphertext_len];
551        read_payload(input, ciphertext)?;
552        let aad = chunk_aad(object_id, header_hash, counter, kind, length);
553        let opened = cipher.open_in_place(&nonce(counter, kind), &aad, ciphertext)?;
554        if kind == FINAL {
555            let mut extra = [0; 1];
556            if read_chunk(input, &mut extra)? != 0 {
557                return Err(ObjectError::TrailingData);
558            }
559        }
560        staging.write_all(&buffer[..opened])?;
561        total += opened as u64;
562        if kind == FINAL {
563            return Ok(total);
564        }
565    }
566    Err(ObjectError::ObjectTooLarge)
567}
568
569fn record_length(kind: u8, ciphertext_len: usize, counter: u64) -> Result<usize, ObjectError> {
570    if !(TAG_LEN..=CHUNK_LEN + TAG_LEN).contains(&ciphertext_len) {
571        return Err(ObjectError::InvalidRecord);
572    }
573    let length = ciphertext_len - TAG_LEN;
574    match kind {
575        DATA if length == CHUNK_LEN => Ok(length),
576        FINAL if length > 0 || counter == 0 => Ok(length),
577        _ => Err(ObjectError::InvalidRecord),
578    }
579}
580
581fn read_payload<R: Read>(reader: &mut R, buffer: &mut [u8]) -> Result<(), ObjectError> {
582    reader.read_exact(buffer).map_err(|error| {
583        if error.kind() == io::ErrorKind::UnexpectedEof {
584            ObjectError::TruncatedPayload
585        } else {
586            ObjectError::Io(error)
587        }
588    })
589}
590
591/// Writes a container whose preamble claims to be signed while carrying no
592/// signature: the shape an attacker produces by stripping one. Test-only.
593#[cfg(feature = "test-vectors")]
594pub fn encrypt_stripped_signature_for_test<R: Read, W: Write>(
595    input: &mut R,
596    output: &mut W,
597    recipients: &[RecipientPublic],
598    metadata: &Metadata,
599    identity: &SigningIdentity,
600) -> Result<u64, ObjectError> {
601    validate_recipients(recipients)?;
602    let material = ObjectMaterial {
603        cek: ContentKey::generate()?,
604        object_id: hide_crypto::random_array()?,
605        payload_salt: hide_crypto::random_array()?,
606    };
607    let stanzas = recipients
608        .iter()
609        .map(|recipient| {
610            hide_crypto::wrap_cek(recipient, &material.cek, &material.object_id).map(|wrapped| {
611                RecipientStanza {
612                    encapsulation: wrapped.encapsulation,
613                    wrapped_cek: wrapped.wrapped_cek,
614                }
615            })
616        })
617        .collect::<Result<Vec<_>, _>>()?;
618    encrypt_inner(
619        input,
620        output,
621        metadata,
622        material,
623        stanzas,
624        Some((identity, SignaturePlacement::Stripped)),
625    )
626}
627
628/// Mounts the forgery a signature must prevent: keep the container's header
629/// byte-for-byte, then re-encrypt different plaintext with the CEK the
630/// recipient already holds. Exposed only for tests, because it exists purely to
631/// prove the signature binds the payload and not merely the header.
632#[cfg(feature = "test-vectors")]
633pub fn forge_payload_for_test(
634    container: &[u8],
635    secret: &RecipientSecret,
636    replacement: &[u8],
637) -> Result<Vec<u8>, ObjectError> {
638    let preamble = Preamble::decode(&container[..PREAMBLE_LEN])?;
639    let header_end = PREAMBLE_LEN + preamble.header_len();
640    let (protected, mac) = hide_format::decode_header(&container[PREAMBLE_LEN..header_end])?;
641    let header = ProtectedHeader::decode(&protected)?;
642    let cek = recover_cek(
643        secret,
644        &header,
645        &container[..PREAMBLE_LEN],
646        &protected,
647        &mac,
648    )?;
649
650    let salt: [u8; 16] = container[header_end..header_end + 16]
651        .try_into()
652        .map_err(|_| ObjectError::TruncatedPayload)?;
653    let key = payload_key(&cek, &header.object_id, &salt)?;
654
655    let mut forged = container[..header_end + 16].to_vec();
656    encrypt_records(
657        &mut &replacement[..],
658        &mut forged,
659        &key,
660        &header.object_id,
661        &hide_crypto::hash(&[&protected]),
662    )?;
663    Ok(forged)
664}
665
666#[cfg(feature = "test-vectors")]
667pub fn encrypt_for_vector<R: Read, W: Write>(
668    input: &mut R,
669    output: &mut W,
670    recipient: &RecipientPublic,
671    metadata: &Metadata,
672) -> Result<u64, ObjectError> {
673    encrypt_for_vector_inner(input, output, recipient, metadata, None)
674}
675
676/// Deterministic signed container, so the vectors are reproducible.
677#[cfg(feature = "test-vectors")]
678pub fn encrypt_signed_for_vector<R: Read, W: Write>(
679    input: &mut R,
680    output: &mut W,
681    recipient: &RecipientPublic,
682    metadata: &Metadata,
683    identity: &SigningIdentity,
684    placement: SignaturePlacement,
685) -> Result<u64, ObjectError> {
686    encrypt_for_vector_inner(
687        input,
688        output,
689        recipient,
690        metadata,
691        Some((identity, placement)),
692    )
693}
694
695#[cfg(feature = "test-vectors")]
696fn encrypt_for_vector_inner<R: Read, W: Write>(
697    input: &mut R,
698    output: &mut W,
699    recipient: &RecipientPublic,
700    metadata: &Metadata,
701    signer: Option<(&SigningIdentity, SignaturePlacement)>,
702) -> Result<u64, ObjectError> {
703    let material = ObjectMaterial {
704        cek: ContentKey::from_bytes([0x11; 32]),
705        object_id: [0x22; 32],
706        payload_salt: [0x33; 16],
707    };
708    let wrapped = hide_crypto::wrap_cek_for_vector(
709        recipient,
710        &material.cek,
711        &material.object_id,
712        [0x44; 32],
713    )?;
714    encrypt_inner(
715        input,
716        output,
717        metadata,
718        material,
719        vec![RecipientStanza {
720            encapsulation: wrapped.encapsulation,
721            wrapped_cek: wrapped.wrapped_cek,
722        }],
723        signer,
724    )
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730
731    fn encrypt_bytes(plaintext: &[u8], secret: &RecipientSecret) -> Result<Vec<u8>, ObjectError> {
732        let mut ciphertext = Vec::new();
733        encrypt(
734            &mut &*plaintext,
735            &mut ciphertext,
736            &[secret.public_key()?],
737            &Metadata::default(),
738        )?;
739        Ok(ciphertext)
740    }
741
742    #[test]
743    fn boundary_sizes_roundtrip() -> Result<(), ObjectError> {
744        let secret = RecipientSecret::generate()?;
745        for size in [
746            0,
747            1,
748            CHUNK_LEN - 1,
749            CHUNK_LEN,
750            CHUNK_LEN + 1,
751            2 * CHUNK_LEN,
752            3 * CHUNK_LEN + 17,
753        ] {
754            let plaintext = vec![0x5a; size];
755            let ciphertext = encrypt_bytes(&plaintext, &secret)?;
756            let mut output = Vec::new();
757            let verified = decrypt_to_staging(&mut ciphertext.as_slice(), &mut output, &secret)?;
758            assert_eq!(verified.plaintext_len, size as u64);
759            assert_eq!(output, plaintext);
760        }
761        Ok(())
762    }
763
764    #[test]
765    fn multiple_recipients_share_one_payload() -> Result<(), ObjectError> {
766        let alice = RecipientSecret::generate()?;
767        let bob = RecipientSecret::generate()?;
768        let mut ciphertext = Vec::new();
769        let metadata = Metadata {
770            filename: Some("hello.txt".into()),
771            media_type: Some("text/plain".into()),
772            signature: None,
773        };
774        encrypt(
775            &mut b"Hello HIDE\n".as_slice(),
776            &mut ciphertext,
777            &[alice.public_key()?, bob.public_key()?],
778            &metadata,
779        )?;
780        for secret in [&alice, &bob] {
781            let mut output = Vec::new();
782            let verified = decrypt_to_staging(&mut ciphertext.as_slice(), &mut output, secret)?;
783            assert_eq!(output, b"Hello HIDE\n");
784            assert_eq!(verified.metadata, metadata);
785        }
786        assert!(!ciphertext.windows(9).any(|window| window == b"hello.txt"));
787        Ok(())
788    }
789
790    #[test]
791    fn rejects_tampering_in_every_container_region() -> Result<(), ObjectError> {
792        let secret = RecipientSecret::generate()?;
793        let ciphertext = encrypt_bytes(&vec![7; CHUNK_LEN + 1], &secret)?;
794        let header_end = PREAMBLE_LEN + Preamble::decode(&ciphertext[..PREAMBLE_LEN])?.header_len();
795        for offset in [
796            8,
797            11,
798            15,
799            30,
800            80,
801            header_end - 1,
802            header_end,
803            header_end + 16,
804            header_end + 20,
805            header_end + 30,
806            ciphertext.len() - 1,
807        ] {
808            let mut damaged = ciphertext.clone();
809            damaged[offset] ^= 1;
810            assert!(
811                decrypt_to_staging(&mut damaged.as_slice(), &mut Vec::new(), &secret).is_err(),
812                "offset {offset}"
813            );
814        }
815        let other = RecipientSecret::generate()?;
816        assert!(decrypt_to_staging(&mut ciphertext.as_slice(), &mut Vec::new(), &other).is_err());
817        Ok(())
818    }
819
820    #[test]
821    fn rejects_missing_final_reordered_duplicate_and_extra_records() -> Result<(), ObjectError> {
822        let secret = RecipientSecret::generate()?;
823        let ciphertext = encrypt_bytes(&vec![7; 2 * CHUNK_LEN + 1], &secret)?;
824        let payload_start =
825            PREAMBLE_LEN + Preamble::decode(&ciphertext[..PREAMBLE_LEN])?.header_len() + 16;
826        let record_len = 5 + CHUNK_LEN + TAG_LEN;
827        let mut reordered = ciphertext.clone();
828        reordered[payload_start..payload_start + record_len].copy_from_slice(
829            &ciphertext[payload_start + record_len..payload_start + 2 * record_len],
830        );
831        let mut duplicated = ciphertext.clone();
832        duplicated.splice(
833            payload_start..payload_start,
834            ciphertext[payload_start..payload_start + record_len]
835                .iter()
836                .copied(),
837        );
838        let mut extra = ciphertext.clone();
839        extra.push(0);
840        for damaged in [
841            ciphertext[..payload_start + 2 * record_len].to_vec(),
842            reordered,
843            duplicated,
844            extra,
845            ciphertext[..ciphertext.len() - 1].to_vec(),
846        ] {
847            assert!(decrypt_to_staging(&mut damaged.as_slice(), &mut Vec::new(), &secret).is_err());
848        }
849        Ok(())
850    }
851
852    #[test]
853    fn rejects_noncanonical_empty_final_and_large_record() {
854        assert!(record_length(FINAL, 16, 1).is_err());
855        assert!(record_length(DATA, 16, 0).is_err());
856        assert!(record_length(FINAL, usize::MAX, 0).is_err());
857        assert!(record_length(3, 17, 0).is_err());
858    }
859
860    #[test]
861    fn chunk_binding_covers_every_field_exactly() {
862        let aad = chunk_aad(
863            &[0xa1; 32],
864            &[0xb2; 32],
865            0x0102_0304_0506_0708,
866            DATA,
867            0x1234,
868        );
869        assert_eq!(&aad[..14], b"HIDE/0.1 chunk");
870        assert_eq!(&aad[14..46], &[0xa1; 32]);
871        assert_eq!(&aad[46..78], &[0xb2; 32]);
872        assert_eq!(&aad[78..86], &[1, 2, 3, 4, 5, 6, 7, 8]);
873        assert_eq!(aad[86], DATA);
874        assert_eq!(&aad[87..], &[0, 0, 0x12, 0x34]);
875
876        let mut contexts = std::collections::HashSet::new();
877        for kind in [DATA, FINAL] {
878            for counter in [0, 1, 2, u32::MAX as u64] {
879                let context = (
880                    chunk_aad(&[0; 32], &[0; 32], counter, kind, 7).to_vec(),
881                    nonce(counter, kind),
882                );
883                assert!(
884                    contexts.insert(context),
885                    "nonce/AAD reuse at {counter}/{kind}"
886                );
887            }
888        }
889        assert_ne!(
890            chunk_aad(&[0; 32], &[0; 32], 0, DATA, 7),
891            chunk_aad(&[0; 32], &[0; 32], 0, FINAL, 7)
892        );
893        assert_eq!(nonce(1, DATA), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]);
894        assert_eq!(nonce(1, FINAL), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]);
895        assert_eq!(
896            nonce(u32::MAX as u64, DATA)[3..11],
897            [0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]
898        );
899    }
900
901    #[test]
902    fn metadata_binding_covers_object_and_suite() {
903        let aad = metadata_aad(&[0xc3; 32]);
904        assert_eq!(&aad[..17], b"HIDE/0.1 metadata");
905        assert_eq!(&aad[17..49], &[0xc3; 32]);
906        assert_eq!(&aad[49..], &[0, 1]);
907        assert_ne!(metadata_aad(&[1; 32]), metadata_aad(&[2; 32]));
908    }
909}