use chacha20poly1305::aead::{Aead, Payload};
use chacha20poly1305::{Key, KeyInit, XChaCha20Poly1305, XNonce};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use crate::compress::TAG_SEALED;
use crate::hash::Hash;
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct StoreKey([u8; 32]);
impl StoreKey {
pub fn new(bytes: [u8; 32]) -> Self {
StoreKey(bytes)
}
}
impl std::fmt::Debug for StoreKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("StoreKey(…)") }
}
const CIPHER_CONTEXT: &str = "zblob v2 2026-07 store chunk cipher key";
const NONCE_CONTEXT: &str = "zblob v2 2026-07 store chunk nonce key";
fn cipher_for(key: &StoreKey) -> XChaCha20Poly1305 {
let k = Zeroizing::new(blake3::derive_key(CIPHER_CONTEXT, &key.0));
XChaCha20Poly1305::new(&Key::from(*k))
}
fn nonce_for(key: &StoreKey, hash: &Hash, container: &[u8]) -> [u8; 24] {
let nk = Zeroizing::new(blake3::derive_key(NONCE_CONTEXT, &key.0));
let mut h = blake3::Hasher::new_keyed(&nk);
h.update(hash.as_bytes());
h.update(container);
let full = h.finalize();
full.as_bytes()[..24].try_into().expect("24 bytes")
}
pub(crate) fn seal(key: &StoreKey, hash: &Hash, container: &[u8]) -> std::io::Result<Vec<u8>> {
let nonce = nonce_for(key, hash, container);
let ciphertext = cipher_for(key)
.encrypt(
&XNonce::from(nonce),
Payload {
msg: container,
aad: hash.as_bytes(),
},
)
.map_err(|_| std::io::Error::other("chunk seal failed"))?;
let mut out = Vec::with_capacity(1 + 24 + ciphertext.len());
out.push(TAG_SEALED);
out.extend_from_slice(&nonce);
out.extend_from_slice(&ciphertext);
Ok(out)
}
pub(crate) fn open(key: &StoreKey, hash: &Hash, sealed: &[u8]) -> Option<Vec<u8>> {
let rest = sealed.strip_prefix(&[TAG_SEALED])?;
if rest.len() < 24 {
return None;
}
let (nonce, ciphertext) = rest.split_at(24);
cipher_for(key)
.decrypt(
&XNonce::try_from(nonce).ok()?,
Payload {
msg: ciphertext,
aad: hash.as_bytes(),
},
)
.ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn key(byte: u8) -> StoreKey {
StoreKey([byte; 32])
}
#[test]
fn seal_open_roundtrip_and_determinism() {
let k = key(1);
let h = Hash::of(b"chunk contents");
let container = b"\x00chunk contents"; let sealed = seal(&k, &h, container).unwrap();
assert_eq!(sealed[0], TAG_SEALED);
assert_eq!(open(&k, &h, &sealed).unwrap(), container);
assert_eq!(seal(&k, &h, container).unwrap(), sealed);
assert!(
!sealed
.windows(b"chunk contents".len())
.any(|w| w == b"chunk contents")
);
}
#[test]
fn tamper_wrong_key_wrong_address_all_fail() {
let k = key(2);
let h = Hash::of(b"data");
let sealed = seal(&k, &h, b"\x00data").unwrap();
let mut flipped = sealed.clone();
let n = flipped.len();
flipped[n - 1] ^= 0xff;
assert!(open(&k, &h, &flipped).is_none(), "tampered must fail");
assert!(open(&key(3), &h, &sealed).is_none(), "wrong key must fail");
let other = Hash::of(b"other chunk");
assert!(
open(&k, &other, &sealed).is_none(),
"ciphertext is bound to its address (AAD)"
);
}
}