vault: one blob cipher for sealing and opening, one HKDF helper
decrypt_blob_chunk re-derived the HKDF content key and rebuilt the cipher for every 64 KiB chunk — 16k expansions per GB — though BlobSealer's own doc explained why the encrypt side avoids exactly that (audit B10). BlobSealer becomes BlobCipher with seal and open; decrypt_blob, BlobStore::load_to_file, BlobStreamSession (which now holds a cipher instead of vault key + hash) and content_fetch build it once per blob. The four HKDF-SHA256-to-32-bytes copies (vault x3, Secret::to_keypair) share hkdf32, and ChaCha20Poly1305 keys are built with the infallible KeyInit::new from a [u8; 32], removing five expects; hkdf32 keeps the one genuinely-infallible expansion expect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b6f71dd96d
commit
e4e779550c
8 files changed
+78
-110
No files matched your search
+1
-1
@@ -1162,7 +1162,7 @@ position. Full structural hiding is a future concern.
|
||||
**Implementation note**: Property and Artifact value columns in SQLite are typed as
|
||||
`BLOB` (not `TEXT`) so that adding at-rest encryption requires no schema migration.
|
||||
The `VaultId` type (`vault::VaultId`, a UUID newtype), the `VaultStore`, and blob
|
||||
content encryption (`vault::BlobSealer`, ADR 0028) are implemented. Encrypting
|
||||
content encryption (`vault::BlobCipher`, ADR 0028) are implemented. Encrypting
|
||||
Property and Artifact *values* under the vault key is the remaining step — until
|
||||
it lands, the vault boundary holds for blob bytes and nothing else, on disk or on
|
||||
the wire.
|
||||
|
||||
@@ -52,7 +52,7 @@ locked domains too.
|
||||
| `VaultId` on every Document, Artifact, BlobRef | **Built** (`vault::VaultId`) |
|
||||
| `VaultStore` — encrypted vault keys in SQLite | **Built** (`stores/vault.rs`), one row per vault: `(vault_id, nonce, ciphertext, updated_at)` |
|
||||
| Default vault key, `EnsembleDerived` via HKDF, wrapped under the node key | **Built** (`vault::derive_ensemble_vault_key`, `encrypt_vault_key`; set up in `ensemble/init.rs`) |
|
||||
| Blob content encryption, convergent, chunked AEAD | **Built** (`vault::BlobSealer`, ADR 0028) |
|
||||
| Blob content encryption, convergent, chunked AEAD | **Built** (`vault::BlobCipher`, ADR 0028) |
|
||||
| Downstream key domains derived from the vault key | **Built** — `derive_blob_content_key`, `NameKey::from_vault_key` (`p2p/sealed_name.rs`), `credentials.rs` |
|
||||
| Property and Artifact **value** encryption | **Not built.** The columns are `BLOB` so it can be added without migration (`stores/document.rs:223`, `stores/artifact.rs:87`), and that is all |
|
||||
| A second vault of any kind | **Not built.** Nothing constructs `VaultKeySpec::Passphrase`; `SharedKey` is a reserved name with no body |
|
||||
@@ -502,7 +502,7 @@ Four items, all in the vault sections, all **corrected**:
|
||||
|
||||
- `docs/data-model.md`: "the actual encryption of Property/Artifact/Blob content
|
||||
under the vault key is the remaining step" — blob content is done (ADR 0028,
|
||||
`vault::BlobSealer`). Only Property and Artifact values remain, and the note
|
||||
`vault::BlobCipher`). Only Property and Artifact values remain, and the note
|
||||
now says which boundary that leaves standing.
|
||||
- `docs/document-sync.md` §Vault identity: "the receiver cannot decrypt the
|
||||
content without the vault key" is true of blob bytes only. Property and
|
||||
|
||||
@@ -48,7 +48,7 @@ use crate::jobs::{JobKind, JobOrigin, JobProgress, JobSubject, ProgressReporter}
|
||||
use crate::p2p::blob_stream::{self, BlobStreamError, BlobStreamSession};
|
||||
use crate::scheduler;
|
||||
use crate::stores::Store;
|
||||
use crate::vault::{BLOB_CHUNK_PLAINTEXT_SIZE, BLOB_CHUNK_STRIDE, decrypt_blob_chunk};
|
||||
use crate::vault::{BLOB_CHUNK_PLAINTEXT_SIZE, BLOB_CHUNK_STRIDE, BlobCipher};
|
||||
|
||||
/// How long one peer gets to hand over the requested range before
|
||||
/// [`fetch_blob_bytes`] gives up on it and tries the next. A peer that accepts
|
||||
@@ -392,6 +392,7 @@ pub fn write_local_blob_to_file(
|
||||
.vault_key(blob_ref.vault_id)
|
||||
.map_err(|e| BlobStreamError::NoVaultKey(e.to_string()))?;
|
||||
let BlobHash::Blake3(plaintext_hash) = blob_ref.plaintext_hash;
|
||||
let cipher = BlobCipher::new(&vault_key, &plaintext_hash);
|
||||
|
||||
let total = blob_store.plaintext_size_of(&blob_ref.blob_hash).unwrap_or(blob_ref.size_bytes);
|
||||
let mut tracker = FetchTracker::new(reporter, total);
|
||||
@@ -411,7 +412,8 @@ pub fn write_local_blob_to_file(
|
||||
// One chunk was asked for, so the read is one stride at most; the
|
||||
// final chunk is short, which is the only case this is not exact.
|
||||
let sealed = &sealed[..sealed.len().min(BLOB_CHUNK_STRIDE)];
|
||||
let plaintext = decrypt_blob_chunk(sealed, &vault_key, &plaintext_hash, chunk_index)
|
||||
let plaintext = cipher
|
||||
.open(sealed, chunk_index)
|
||||
.map_err(|_| BlobStreamError::ChunkAuthenticationFailed)?;
|
||||
file.write_all(&plaintext)?;
|
||||
tracker.advance(plaintext.len() as u64);
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
use hkdf::Hkdf;
|
||||
use iroh::SecretKey;
|
||||
use rand::TryRng;
|
||||
use rand::rngs::SysRng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::Sha256;
|
||||
use ur::bytewords::{self, Style};
|
||||
|
||||
use super::diceware::{self, DicewareError};
|
||||
use crate::vault::hkdf32;
|
||||
|
||||
/// Joins the two words of a format B display group (`"slouch·jaywalk"`).
|
||||
///
|
||||
@@ -307,12 +306,7 @@ impl<S: SecretKind> Secret<S> {
|
||||
/// separation between `NodeSecret` and `EnsembleSecret` comes from the per-kind
|
||||
/// `HKDF_INFO` tag.
|
||||
pub fn to_keypair(&self) -> Keypair<S> {
|
||||
let ikm = self.ikm_bytes();
|
||||
let hk = Hkdf::<Sha256>::new(None, &ikm);
|
||||
let mut derived_key = [0u8; 32];
|
||||
hk.expand(S::HKDF_INFO, &mut derived_key)
|
||||
.expect("HKDF-SHA256 expansion to 32 bytes is always within the allowed length");
|
||||
|
||||
let derived_key = hkdf32(None, &self.ikm_bytes(), S::HKDF_INFO);
|
||||
let secret_key = SecretKey::from_bytes(&derived_key);
|
||||
|
||||
Keypair { secret: self.clone(), secret_key }
|
||||
|
||||
@@ -60,7 +60,7 @@ use crate::p2p::admission::{CertifiedPeer, EnsembleEndpoint, EnsembleProtocol};
|
||||
use crate::p2p::wire::{self, WireError, read_msg, write_msg};
|
||||
use crate::stores::Store;
|
||||
use crate::stores::blob_store::BlobStore;
|
||||
use crate::vault::{self, BLOB_CHUNK_PLAINTEXT_SIZE, BLOB_CHUNK_STRIDE, VaultKey};
|
||||
use crate::vault::{BLOB_CHUNK_PLAINTEXT_SIZE, BLOB_CHUNK_STRIDE, BlobCipher};
|
||||
|
||||
pub const BLOB_STREAM_ALPN: &[u8] = b"/syn/blob-stream/3";
|
||||
|
||||
@@ -289,8 +289,7 @@ pub struct BlobStreamSession {
|
||||
/// BLOB_CHUNK_PLAINTEXT_SIZE` and increments by one per chunk — safe
|
||||
/// because the QUIC stream delivers chunks in order.
|
||||
next_chunk_index: u64,
|
||||
vault_key: VaultKey,
|
||||
plaintext_hash: [u8; 32],
|
||||
cipher: BlobCipher,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
@@ -323,13 +322,10 @@ impl BlobStreamSession {
|
||||
|
||||
let chunk_index = self.next_chunk_index;
|
||||
self.next_chunk_index += 1;
|
||||
let plaintext = vault::decrypt_blob_chunk(
|
||||
&chunk.data,
|
||||
&self.vault_key,
|
||||
&self.plaintext_hash,
|
||||
chunk_index,
|
||||
)
|
||||
.map_err(|_| BlobStreamError::ChunkAuthenticationFailed)?;
|
||||
let plaintext = self
|
||||
.cipher
|
||||
.open(&chunk.data, chunk_index)
|
||||
.map_err(|_| BlobStreamError::ChunkAuthenticationFailed)?;
|
||||
|
||||
let chunk_plain_start = chunk_index * BLOB_CHUNK_PLAINTEXT_SIZE as u64;
|
||||
let (lo, hi) = trim_chunk_bounds(
|
||||
@@ -414,8 +410,7 @@ pub async fn open_blob_stream(
|
||||
actual_start_byte: header.actual_start_byte,
|
||||
end_byte,
|
||||
next_chunk_index: header.actual_start_byte / BLOB_CHUNK_PLAINTEXT_SIZE as u64,
|
||||
vault_key,
|
||||
plaintext_hash,
|
||||
cipher: BlobCipher::new(&vault_key, &plaintext_hash),
|
||||
finished: false,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -209,8 +209,7 @@ impl SealedName {
|
||||
}
|
||||
|
||||
fn cipher(key: &NameKey) -> ChaCha20Poly1305 {
|
||||
ChaCha20Poly1305::new_from_slice(&key.0)
|
||||
.expect("32-byte name key is always valid for ChaCha20-Poly1305")
|
||||
ChaCha20Poly1305::new(&key.0.into())
|
||||
}
|
||||
|
||||
/// Length of the padded plaintext for a name of `name_len` bytes: the 2-byte
|
||||
|
||||
@@ -10,9 +10,8 @@ use crate::documents::BlobHash;
|
||||
use crate::stores::settings::SettingsStore;
|
||||
use crate::stores::vault::VaultStore;
|
||||
use crate::vault::{
|
||||
BLOB_CHUNK_PLAINTEXT_SIZE, BLOB_CHUNK_STRIDE, BlobSealer, VaultId, VaultKey, blob_chunk_count,
|
||||
blob_chunk_range, decrypt_blob, decrypt_blob_chunk, decrypt_vault_key,
|
||||
plaintext_size_from_ciphertext_len,
|
||||
BLOB_CHUNK_PLAINTEXT_SIZE, BLOB_CHUNK_STRIDE, BlobCipher, VaultId, VaultKey, blob_chunk_count,
|
||||
blob_chunk_range, decrypt_blob, decrypt_vault_key, plaintext_size_from_ciphertext_len,
|
||||
};
|
||||
|
||||
use types::BlobId;
|
||||
@@ -250,7 +249,7 @@ impl BlobStore {
|
||||
plaintext_hash: &[u8; 32],
|
||||
progress: Option<&dyn StoreProgress>,
|
||||
) -> Result<(BlobHash, TempBlob), BlobStoreError> {
|
||||
let sealer = BlobSealer::new(vault_key, plaintext_hash);
|
||||
let sealer = BlobCipher::new(vault_key, plaintext_hash);
|
||||
let temp = TempBlob::create(&self.root)?;
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
{
|
||||
@@ -327,7 +326,7 @@ impl BlobStore {
|
||||
plaintext_hash: &[u8; 32],
|
||||
progress: Option<&dyn StoreProgress>,
|
||||
) -> Result<(BlobHash, TempBlob), BlobStoreError> {
|
||||
let sealer = BlobSealer::new(vault_key, plaintext_hash);
|
||||
let sealer = BlobCipher::new(vault_key, plaintext_hash);
|
||||
let temp = TempBlob::create(&self.root)?;
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
{
|
||||
@@ -364,7 +363,7 @@ impl BlobStore {
|
||||
/// the end without a third pass, so it doesn't — every chunk is still
|
||||
/// individually authenticated by its AEAD tag over an associated-data
|
||||
/// block that binds the blob's plaintext hash and the chunk's index (see
|
||||
/// [`decrypt_blob_chunk`](crate::vault::decrypt_blob_chunk)), so a
|
||||
/// [`BlobCipher::open`]), so a
|
||||
/// substituted, reordered or truncated-mid-chunk file fails here. What is
|
||||
/// lost is only the detection of a file truncated on an exact chunk
|
||||
/// boundary, which the caller's own use of the bytes will notice.
|
||||
@@ -384,6 +383,7 @@ impl BlobStore {
|
||||
|
||||
let mut input = fs::File::open(&path)?;
|
||||
let mut out = BufWriter::new(fs::File::create(out_path)?);
|
||||
let cipher = BlobCipher::new(&vault_key, plaintext_hash_bytes);
|
||||
let mut sealed = vec![0u8; BLOB_CHUNK_STRIDE];
|
||||
let mut written = 0u64;
|
||||
let mut index = 0u64;
|
||||
@@ -392,9 +392,9 @@ impl BlobStore {
|
||||
if filled == 0 {
|
||||
break;
|
||||
}
|
||||
let plain =
|
||||
decrypt_blob_chunk(&sealed[..filled], &vault_key, plaintext_hash_bytes, index)
|
||||
.map_err(|_| BlobStoreError::DecryptionError(stored_hash.clone()))?;
|
||||
let plain = cipher
|
||||
.open(&sealed[..filled], index)
|
||||
.map_err(|_| BlobStoreError::DecryptionError(stored_hash.clone()))?;
|
||||
out.write_all(&plain)?;
|
||||
written += plain.len() as u64;
|
||||
index += 1;
|
||||
@@ -869,16 +869,10 @@ mod tests {
|
||||
|
||||
// Decrypting just that chunk (at its real index) matches the plaintext at
|
||||
// the corresponding offset — the whole point of the range read.
|
||||
let plain = crate::vault::decrypt_blob_chunk(
|
||||
&one_chunk,
|
||||
&store.vault_key(DEFAULT_VAULT_ID).unwrap(),
|
||||
&{
|
||||
let BlobHash::Blake3(h) = blob.plaintext_hash;
|
||||
h
|
||||
},
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
let BlobHash::Blake3(plaintext_hash) = blob.plaintext_hash;
|
||||
let plain = BlobCipher::new(&store.vault_key(DEFAULT_VAULT_ID).unwrap(), &plaintext_hash)
|
||||
.open(&one_chunk, 1)
|
||||
.unwrap();
|
||||
let expected_start = crate::vault::BLOB_CHUNK_PLAINTEXT_SIZE;
|
||||
assert_eq!(plain, data[expected_start..expected_start * 2]);
|
||||
}
|
||||
|
||||
+48
-64
@@ -176,13 +176,20 @@ pub fn derive_ensemble_vault_key(
|
||||
label: &str,
|
||||
version: u32,
|
||||
) -> VaultKey {
|
||||
let ikm = ensemble_secret_key.to_bytes();
|
||||
let info = format!("syn:vault:ensemble-derived:{label}:v{version}");
|
||||
let hk = Hkdf::<Sha256>::new(None, ikm.as_ref());
|
||||
VaultKey(hkdf32(None, &ensemble_secret_key.to_bytes(), info.as_bytes()))
|
||||
}
|
||||
|
||||
/// HKDF-SHA256, expanded to one 32-byte key — the only length this crate
|
||||
/// derives.
|
||||
pub(crate) fn hkdf32(salt: Option<&[u8]>, ikm: &[u8], info: &[u8]) -> [u8; 32] {
|
||||
let mut out = [0u8; 32];
|
||||
hk.expand(info.as_bytes(), &mut out)
|
||||
// HKDF-SHA256 can expand to 255 * 32 bytes; 32 is always within that,
|
||||
// so this is the one `expect` every derivation here shares.
|
||||
Hkdf::<Sha256>::new(salt, ikm)
|
||||
.expand(info, &mut out)
|
||||
.expect("HKDF-SHA256 expansion to 32 bytes is always within the allowed length");
|
||||
VaultKey(out)
|
||||
out
|
||||
}
|
||||
|
||||
/// Associated data binding a wrapped vault key to the vault it belongs to.
|
||||
@@ -211,9 +218,7 @@ pub fn encrypt_vault_key(
|
||||
vault_key: &VaultKey,
|
||||
node_secret_key: &iroh::SecretKey,
|
||||
) -> Result<EncryptedVaultKey, VaultError> {
|
||||
let wrapping_key = derive_node_enc_key(node_secret_key);
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&wrapping_key)
|
||||
.expect("32-byte wrapping key is always valid for ChaCha20-Poly1305");
|
||||
let cipher = ChaCha20Poly1305::new(&derive_node_enc_key(node_secret_key).into());
|
||||
|
||||
let mut nonce_bytes = [0u8; 12];
|
||||
SysRng
|
||||
@@ -246,9 +251,7 @@ pub fn decrypt_vault_key(
|
||||
encrypted: &EncryptedVaultKey,
|
||||
node_secret_key: &iroh::SecretKey,
|
||||
) -> Result<VaultKey, VaultError> {
|
||||
let wrapping_key = derive_node_enc_key(node_secret_key);
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&wrapping_key)
|
||||
.expect("32-byte wrapping key is always valid for ChaCha20-Poly1305");
|
||||
let cipher = ChaCha20Poly1305::new(&derive_node_enc_key(node_secret_key).into());
|
||||
|
||||
let nonce = Nonce::from(encrypted.nonce);
|
||||
let mut buf = encrypted.ciphertext.to_vec();
|
||||
@@ -267,12 +270,7 @@ pub fn decrypt_vault_key(
|
||||
/// Built from the node's Ed25519 secret key bytes via HKDF-SHA256 with a
|
||||
/// domain-separating info tag. Never leaves the device.
|
||||
fn derive_node_enc_key(node_secret_key: &iroh::SecretKey) -> [u8; 32] {
|
||||
let ikm = node_secret_key.to_bytes();
|
||||
let hk = Hkdf::<Sha256>::new(None, ikm.as_ref());
|
||||
let mut out = [0u8; 32];
|
||||
hk.expand(HKDF_INFO_VAULT_WRAP, &mut out)
|
||||
.expect("HKDF-SHA256 expansion to 32 bytes is always within the allowed length");
|
||||
out
|
||||
hkdf32(None, &node_secret_key.to_bytes(), HKDF_INFO_VAULT_WRAP)
|
||||
}
|
||||
|
||||
/// Plaintext bytes sealed per AEAD chunk. Chosen to match
|
||||
@@ -295,11 +293,7 @@ pub const BLOB_CHUNK_STRIDE: usize = BLOB_CHUNK_PLAINTEXT_SIZE + BLOB_CHUNK_TAG_
|
||||
/// two nodes that independently encrypt the same plaintext under the same vault key
|
||||
/// will produce identical ciphertext.
|
||||
pub fn derive_blob_content_key(vault_key: &VaultKey, plaintext_hash: &[u8; 32]) -> [u8; 32] {
|
||||
let hk = Hkdf::<Sha256>::new(Some(plaintext_hash), vault_key.as_bytes());
|
||||
let mut out = [0u8; 32];
|
||||
hk.expand(b"syn:blob:content-key:v1", &mut out)
|
||||
.expect("HKDF-SHA256 expansion to 32 bytes is always within the allowed length");
|
||||
out
|
||||
hkdf32(Some(plaintext_hash), vault_key.as_bytes(), b"syn:blob:content-key:v1")
|
||||
}
|
||||
|
||||
/// Per-chunk nonce: the chunk index as a big-endian counter in the low 8
|
||||
@@ -326,32 +320,32 @@ fn blob_chunk_associated_data(plaintext_hash: &[u8; 32], chunk_index: u64) -> Ve
|
||||
ad
|
||||
}
|
||||
|
||||
/// Seals one blob's chunks, one at a time.
|
||||
/// Seals and opens one blob's chunks, one at a time.
|
||||
///
|
||||
/// Two reasons this is a value rather than a free function per chunk. It lets
|
||||
/// a caller stream ciphertext out — sealing chunk *i*, writing it, and
|
||||
/// forgetting it — instead of building the whole thing in memory first, which
|
||||
/// is what [`BlobStore::store`](crate::stores::blob_store::BlobStore::store)
|
||||
/// does. And it derives the per-blob content key and builds the cipher once
|
||||
/// for the blob rather than once per 64 KiB: at a gigabyte that is one HKDF
|
||||
/// expansion instead of sixteen thousand.
|
||||
/// a caller stream ciphertext in or out — handling chunk *i* and forgetting
|
||||
/// it — instead of holding the whole blob in memory. And it derives the
|
||||
/// per-blob content key and builds the cipher once for the blob rather than
|
||||
/// once per 64 KiB: at a gigabyte that is one HKDF expansion instead of
|
||||
/// sixteen thousand.
|
||||
///
|
||||
/// The bytes it produces are exactly [`encrypt_blob`]'s — that function is
|
||||
/// written in terms of this one — so nothing about the on-disk or on-wire
|
||||
/// format depends on which is used.
|
||||
pub struct BlobSealer {
|
||||
pub struct BlobCipher {
|
||||
cipher: ChaCha20Poly1305,
|
||||
plaintext_hash: [u8; 32],
|
||||
}
|
||||
|
||||
impl BlobSealer {
|
||||
impl BlobCipher {
|
||||
/// `plaintext_hash` must be `BLAKE3(plaintext)` of the whole blob — it
|
||||
/// drives the content key derivation, so a sealer is bound to one blob.
|
||||
/// drives the content key derivation, so a cipher is bound to one blob.
|
||||
pub fn new(vault_key: &VaultKey, plaintext_hash: &[u8; 32]) -> Self {
|
||||
let content_key = derive_blob_content_key(vault_key, plaintext_hash);
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&content_key)
|
||||
.expect("32-byte content key is always valid for ChaCha20-Poly1305");
|
||||
BlobSealer { cipher, plaintext_hash: *plaintext_hash }
|
||||
BlobCipher {
|
||||
cipher: ChaCha20Poly1305::new(&content_key.into()),
|
||||
plaintext_hash: *plaintext_hash,
|
||||
}
|
||||
}
|
||||
|
||||
/// Seal one chunk's plaintext (at most [`BLOB_CHUNK_PLAINTEXT_SIZE`]
|
||||
@@ -370,6 +364,21 @@ impl BlobSealer {
|
||||
.map_err(|_| VaultError::Crypto("blob chunk encryption failed".into()))?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Open one sealed chunk. `chunk_index` must be the same index it was
|
||||
/// sealed with — the nonce and associated data both depend on it, so a
|
||||
/// mismatched index (or a chunk reordered/substituted by whoever is
|
||||
/// relaying it) fails authentication rather than decrypting to the wrong
|
||||
/// bytes.
|
||||
pub fn open(&self, sealed: &[u8], chunk_index: u64) -> Result<Vec<u8>, VaultError> {
|
||||
let nonce = Nonce::from(blob_chunk_nonce(chunk_index));
|
||||
let ad = blob_chunk_associated_data(&self.plaintext_hash, chunk_index);
|
||||
let mut buf = sealed.to_vec();
|
||||
self.cipher
|
||||
.decrypt_in_place(&nonce, ad.as_slice(), &mut buf)
|
||||
.map_err(|_| VaultError::DecryptionFailed)?;
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many [`BLOB_CHUNK_PLAINTEXT_SIZE`] chunks a blob of `plaintext_len`
|
||||
@@ -390,32 +399,6 @@ pub fn blob_chunk_range(index: usize, plaintext_len: usize) -> std::ops::Range<u
|
||||
start..end
|
||||
}
|
||||
|
||||
/// Open one sealed chunk. `chunk_index` must be the same index it was
|
||||
/// sealed with — the nonce and associated data both depend on it, so a
|
||||
/// mismatched index (or a chunk reordered/substituted by whoever is
|
||||
/// relaying it) fails authentication rather than decrypting to the wrong
|
||||
/// bytes. `pub(crate)` (rather than folded entirely into [`decrypt_blob`])
|
||||
/// because `p2p::blob_stream`'s client decrypts each wire chunk as it
|
||||
/// arrives, without ever holding the full ciphertext.
|
||||
pub(crate) fn decrypt_blob_chunk(
|
||||
sealed: &[u8],
|
||||
vault_key: &VaultKey,
|
||||
plaintext_hash: &[u8; 32],
|
||||
chunk_index: u64,
|
||||
) -> Result<Vec<u8>, VaultError> {
|
||||
let content_key = derive_blob_content_key(vault_key, plaintext_hash);
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&content_key)
|
||||
.expect("32-byte content key is always valid for ChaCha20-Poly1305");
|
||||
let nonce_bytes = blob_chunk_nonce(chunk_index);
|
||||
let nonce = Nonce::from(nonce_bytes);
|
||||
let ad = blob_chunk_associated_data(plaintext_hash, chunk_index);
|
||||
let mut buf = sealed.to_vec();
|
||||
cipher
|
||||
.decrypt_in_place(&nonce, ad.as_slice(), &mut buf)
|
||||
.map_err(|_| VaultError::DecryptionFailed)?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Encrypt blob plaintext, producing ciphertext: [`BLOB_CHUNK_PLAINTEXT_SIZE`]-byte
|
||||
/// chunks, each independently sealed (chunk bytes + 16-byte AEAD tag) and
|
||||
/// concatenated. Chunking (see ADR 0028) lets a chunk be authenticated and
|
||||
@@ -432,7 +415,7 @@ pub fn encrypt_blob(
|
||||
plaintext_hash: &[u8; 32],
|
||||
) -> Result<Vec<u8>, VaultError> {
|
||||
let num_chunks = blob_chunk_count(data.len());
|
||||
let sealer = BlobSealer::new(vault_key, plaintext_hash);
|
||||
let sealer = BlobCipher::new(vault_key, plaintext_hash);
|
||||
let mut out = Vec::with_capacity(data.len() + num_chunks * BLOB_CHUNK_TAG_SIZE);
|
||||
for i in 0..num_chunks {
|
||||
out.extend_from_slice(&sealer.seal(&data[blob_chunk_range(i, data.len())], i as u64)?);
|
||||
@@ -456,9 +439,10 @@ pub fn decrypt_blob(
|
||||
if ciphertext.is_empty() {
|
||||
return Err(VaultError::DecryptionFailed);
|
||||
}
|
||||
let cipher = BlobCipher::new(vault_key, plaintext_hash);
|
||||
let mut out = Vec::with_capacity(ciphertext.len());
|
||||
for (i, sealed) in ciphertext.chunks(BLOB_CHUNK_STRIDE).enumerate() {
|
||||
out.extend_from_slice(&decrypt_blob_chunk(sealed, vault_key, plaintext_hash, i as u64)?);
|
||||
out.extend_from_slice(&cipher.open(sealed, i as u64)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -757,7 +741,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decrypt_blob_chunk_at_matches_whole_blob_decrypt() {
|
||||
fn opening_one_chunk_matches_whole_blob_decrypt() {
|
||||
let vault_key = VaultKey([9u8; 32]);
|
||||
let plaintext = vec![0x42u8; BLOB_CHUNK_PLAINTEXT_SIZE + 100];
|
||||
let plaintext_hash = *blake3::hash(&plaintext).as_bytes();
|
||||
@@ -765,7 +749,7 @@ mod tests {
|
||||
|
||||
let second_sealed_chunk = &ciphertext[BLOB_CHUNK_STRIDE..];
|
||||
let plain_chunk =
|
||||
decrypt_blob_chunk(second_sealed_chunk, &vault_key, &plaintext_hash, 1).unwrap();
|
||||
BlobCipher::new(&vault_key, &plaintext_hash).open(second_sealed_chunk, 1).unwrap();
|
||||
assert_eq!(plain_chunk, plaintext[BLOB_CHUNK_PLAINTEXT_SIZE..]);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user