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