hexz_core/algo/encryption/mod.rs
1//! Encryption primitives for snapshot blocks.
2//!
3//! Provides the `Encryptor` trait and concrete implementations (AES-256-GCM).
4
5use hexz_common::Result;
6use std::fmt::Debug;
7
8/// Pluggable interface for per-block authenticated encryption.
9///
10/// **Architectural intent:** Abstracts over concrete AEAD algorithms while
11/// preserving the requirement that each logical block be independently
12/// decryptable and integrity-protected.
13///
14/// **Constraints:** Implementations must treat `block_idx` as part of the
15/// nonce or associated data so that reordering or duplication can be detected.
16pub trait Encryptor: Send + Sync + Debug {
17 /// Encrypts and authenticates a logical block.
18 ///
19 /// **Architectural intent:** Produces a ciphertext that can be stored in
20 /// the snapshot data region and later verified during reads.
21 ///
22 /// **Constraints:** `block_idx` must uniquely identify the block within
23 /// the snapshot under a given key; reusing indices can break security.
24 fn encrypt(&self, data: &[u8], block_idx: u64) -> Result<Vec<u8>>;
25
26 /// Decrypts and verifies a logical block.
27 ///
28 /// **Architectural intent:** Recovers the original plaintext or surfaces a
29 /// hard error if tampering or key mismatch is detected.
30 ///
31 /// **Constraints:** Callers must pass the same `block_idx` used on
32 /// encryption; failures should be treated as fatal for the affected block.
33 fn decrypt(&self, data: &[u8], block_idx: u64) -> Result<Vec<u8>>;
34
35 /// Encrypts into a caller-provided buffer, enabling buffer reuse.
36 ///
37 /// **Default impl:** Falls back to `encrypt()` and copies the result.
38 fn encrypt_into(&self, data: &[u8], block_idx: u64, out: &mut Vec<u8>) -> Result<()> {
39 let encrypted = self.encrypt(data, block_idx)?;
40 out.clear();
41 out.extend_from_slice(&encrypted);
42 Ok(())
43 }
44
45 /// Decrypts into a caller-provided buffer, enabling buffer reuse.
46 ///
47 /// **Default impl:** Falls back to `decrypt()` and copies the result.
48 fn decrypt_into(&self, data: &[u8], block_idx: u64, out: &mut Vec<u8>) -> Result<()> {
49 let decrypted = self.decrypt(data, block_idx)?;
50 out.clear();
51 out.extend_from_slice(&decrypted);
52 Ok(())
53 }
54}
55
56/// AES-256-GCM encryption backend.
57pub mod aes_gcm;
58
59pub use aes_gcm::AesGcmEncryptor;