Cotton code
79 lines · 3.0 KB · RustRaw
//! A picture's file, sealed on the phone with a key of its own before it goes//! to the chat file store; the key travels inside the message's boxes, so the//! store, and the Worker, hold only ciphertext.//!//! ```text//! file = "cf1" || nonce(12) || AES-256-GCM(file_key, nonce, plain, aad = "cotton-chat-file-v1")//! ```use aes_gcm::aead::{Aead, Payload};use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};use rand::RngCore;use sha2::{Digest, Sha256};use zeroize::Zeroizing;const MAGIC: &[u8] = b"cf1";const AAD: &[u8] = b"cotton-chat-file-v1";/// A picture at most, plain: what the store takes.pub const FILE_MAX: usize = 16 * 1024 * 1024;/// How long after a Cotton message is written, or lands on this phone, that/// its file is never called gone (FEEDBACK1 item 1, 22 Nov 2026): a picture/// asked for while it is still going up, or by a phone the message reached/// before the store had settled, is "not yet", never "not available".pub const GONE_NOT_BEFORE_MS: i64 = 10 * 60 * 1000;/// Whether a missing file of a Cotton message may be said gone now: never while/// the message is still on its way out (`sending`), and never within/// [`GONE_NOT_BEFORE_MS`] of `at_ms` (the later of when it was written and when/// it landed here). A message whose time is not known may be.pub fn may_be_gone(sending: bool, at_ms: Option<i64>, now_ms: i64) -> bool {    !sending && at_ms.is_none_or(|at| now_ms - at >= GONE_NOT_BEFORE_MS)}/// A sealed file, its key and the plain file's hash.pub struct Sealed {    pub bytes: Vec<u8>,    pub key: Zeroizing<[u8; 32]>,    pub sha256: String,}pub fn seal_file(plain: &[u8]) -> Option<Sealed> {    let mut key = Zeroizing::new([0u8; 32]);    let mut nonce = [0u8; 12];    rand::rngs::OsRng.fill_bytes(key.as_mut_slice());    rand::rngs::OsRng.fill_bytes(&mut nonce);    seal_file_with(&key, &nonce, plain).map(|bytes| Sealed { bytes, key, sha256: sha256_hex(plain) })}pub fn seal_file_with(key: &[u8; 32], nonce: &[u8; 12], plain: &[u8]) -> Option<Vec<u8>> {    if plain.len() > FILE_MAX {        return None;    }    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));    let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg: plain, aad: AAD }).ok()?;    let mut out = Vec::with_capacity(MAGIC.len() + 12 + ct.len());    out.extend_from_slice(MAGIC);    out.extend_from_slice(nonce);    out.extend_from_slice(&ct);    Some(out)}/// Open a sealed file and check it is the one the message named.pub fn open_file(key: &[u8; 32], sealed: &[u8], sha256: &str) -> Option<Vec<u8>> {    let rest = sealed.strip_prefix(MAGIC)?;    if rest.len() < 12 + 16 {        return None;    }    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));    let plain = cipher.decrypt(Nonce::from_slice(&rest[..12]), Payload { msg: &rest[12..], aad: AAD }).ok()?;    (sha256_hex(&plain) == sha256.to_ascii_lowercase()).then_some(plain)}pub fn sha256_hex(bytes: &[u8]) -> String {    Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()}#[cfg(test)]#[path = "files_tests.rs"]mod tests;