mnemo/crypto.rs
1//! Cryptography layer for Mnemo (Phase 4 of the build plan).
2//!
3//! Mnemo uses a **two-tier key hierarchy**:
4//!
5//! ```text
6//! passphrase ──Argon2id──▶ KEK (key-encryption-key)
7//! │ AES-256-GCM
8//! ▼
9//! DEK (data-encryption-key, random 256-bit)
10//! │ AES-256-GCM, per-page
11//! ▼
12//! encrypted pages on disk
13//! ```
14//!
15//! The DEK encrypts every page. The KEK only ever encrypts ("wraps") the DEK.
16//! This is what makes `rekey` cheap: changing the passphrase re-derives the KEK
17//! and re-wraps the DEK — the pages themselves never need re-encryption.
18//!
19//! Every page gets a unique nonce derived from `(page_number, write_counter)`,
20//! where `write_counter` is a monotonic counter persisted in the file header.
21//! Because the counter never repeats, an AES-GCM nonce is never reused.
22
23use aes_gcm::aead::{Aead, KeyInit, Payload};
24use aes_gcm::{Aes256Gcm, Key, Nonce};
25use argon2::{Algorithm, Argon2, Params, Version};
26use zeroize::Zeroizing;
27
28use crate::error::{MnemoError, Result};
29
30/// Length of a symmetric key in bytes (256-bit).
31pub const KEY_LEN: usize = 32;
32/// Length of an AES-GCM nonce in bytes (96-bit).
33pub const NONCE_LEN: usize = 12;
34/// Length of an AES-GCM authentication tag in bytes.
35pub const TAG_LEN: usize = 16;
36/// Length of the Argon2 salt in bytes.
37pub const SALT_LEN: usize = 16;
38
39/// Argon2id cost parameters. Stored (unencrypted) in the file header so the
40/// KEK can be re-derived on open.
41#[derive(Clone, Copy, Debug)]
42pub struct KdfParams {
43 /// Memory cost in KiB.
44 pub m_cost: u32,
45 /// Time cost (number of iterations).
46 pub t_cost: u32,
47 /// Parallelism (lanes).
48 pub p_cost: u32,
49}
50
51impl KdfParams {
52 /// Sensible interactive-use defaults (~19 MiB, 2 passes).
53 pub fn secure() -> Self {
54 Self { m_cost: 19_456, t_cost: 2, p_cost: 1 }
55 }
56
57 /// Deliberately weak parameters — **only** for fast unit tests.
58 #[doc(hidden)]
59 pub fn fast() -> Self {
60 Self { m_cost: 512, t_cost: 1, p_cost: 1 }
61 }
62}
63
64impl Default for KdfParams {
65 fn default() -> Self {
66 Self::secure()
67 }
68}
69
70/// Derive the key-encryption-key (KEK) from a passphrase using Argon2id.
71pub fn derive_kek(
72 passphrase: &[u8],
73 salt: &[u8],
74 params: KdfParams,
75) -> Result<Zeroizing<[u8; KEY_LEN]>> {
76 let p = Params::new(params.m_cost, params.t_cost, params.p_cost, Some(KEY_LEN))
77 .map_err(|e| MnemoError::Kdf(e.to_string()))?;
78 let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, p);
79 let mut key = Zeroizing::new([0u8; KEY_LEN]);
80 argon
81 .hash_password_into(passphrase, salt, &mut key[..])
82 .map_err(|e| MnemoError::Kdf(e.to_string()))?;
83 Ok(key)
84}
85
86fn cipher(key: &[u8; KEY_LEN]) -> Aes256Gcm {
87 Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key))
88}
89
90/// AES-256-GCM encrypt with **Associated Authenticated Data**. The AAD is not
91/// part of the ciphertext but is bound into the authentication tag; decryption
92/// fails unless the caller supplies the same AAD. Output is
93/// `ciphertext || 16-byte tag`.
94///
95/// Pass `&[]` to encrypt without AAD — this matches the format before v6, used
96/// for wrapping the DEK and for v4/v5 page encryption. From v6 onwards, page
97/// encryption passes `page_no.to_le_bytes()` as AAD so an attacker can't
98/// transplant a valid encrypted page to a different page slot — the
99/// authentication tag binds the page image to its home page number.
100pub fn aead_encrypt(
101 key: &[u8; KEY_LEN],
102 nonce: &[u8; NONCE_LEN],
103 plaintext: &[u8],
104 aad: &[u8],
105) -> Result<Vec<u8>> {
106 cipher(key)
107 .encrypt(Nonce::from_slice(nonce), Payload { msg: plaintext, aad })
108 .map_err(|e| MnemoError::Crypto(e.to_string()))
109}
110
111/// AES-256-GCM decrypt with AAD. Input must be `ciphertext || 16-byte tag`.
112/// Returns an error if authentication fails — including when the supplied
113/// AAD doesn't match what was used during encryption.
114pub fn aead_decrypt(
115 key: &[u8; KEY_LEN],
116 nonce: &[u8; NONCE_LEN],
117 ciphertext: &[u8],
118 aad: &[u8],
119) -> Result<Vec<u8>> {
120 cipher(key)
121 .decrypt(Nonce::from_slice(nonce), Payload { msg: ciphertext, aad })
122 .map_err(|_| MnemoError::Crypto("authentication failed".into()))
123}
124
125/// Generate a fresh random 256-bit data-encryption-key.
126pub fn random_dek() -> Zeroizing<[u8; KEY_LEN]> {
127 use rand::RngCore;
128 let mut dek = Zeroizing::new([0u8; KEY_LEN]);
129 rand::thread_rng().fill_bytes(&mut dek[..]);
130 dek
131}
132
133/// Generate a random Argon2 salt.
134pub fn random_salt() -> [u8; SALT_LEN] {
135 use rand::RngCore;
136 let mut salt = [0u8; SALT_LEN];
137 rand::thread_rng().fill_bytes(&mut salt);
138 salt
139}
140
141/// Generate a random nonce (used for wrapping the DEK).
142pub fn random_nonce() -> [u8; NONCE_LEN] {
143 use rand::RngCore;
144 let mut n = [0u8; NONCE_LEN];
145 rand::thread_rng().fill_bytes(&mut n);
146 n
147}
148
149/// Build a deterministic, unique page nonce from a page number and the
150/// monotonic write counter. `(page, counter)` never repeats, so neither does
151/// the nonce — the central safety property of the encryption scheme.
152pub fn page_nonce(page_no: u64, write_counter: u64) -> [u8; NONCE_LEN] {
153 let mut n = [0u8; NONCE_LEN];
154 n[0..4].copy_from_slice(&(page_no as u32).to_le_bytes());
155 n[4..12].copy_from_slice(&write_counter.to_le_bytes());
156 n
157}
158
159/// Wrap (encrypt) the DEK with the KEK. The wrap uses **empty AAD** in every
160/// version, so v5 wrapped-DEK bytes on disk round-trip unchanged through a v6
161/// build — only page encryption changed in v6.
162pub fn wrap_dek(
163 kek: &[u8; KEY_LEN],
164 nonce: &[u8; NONCE_LEN],
165 dek: &[u8; KEY_LEN],
166) -> Result<Vec<u8>> {
167 aead_encrypt(kek, nonce, dek, &[])
168}
169
170/// Unwrap (decrypt) the DEK with the KEK. A wrong KEK (wrong passphrase)
171/// fails authentication and is reported as [`MnemoError::WrongPassphrase`].
172pub fn unwrap_dek(
173 kek: &[u8; KEY_LEN],
174 nonce: &[u8; NONCE_LEN],
175 wrapped: &[u8],
176) -> Result<Zeroizing<[u8; KEY_LEN]>> {
177 let plain = cipher(kek)
178 .decrypt(
179 Nonce::from_slice(nonce),
180 Payload { msg: wrapped, aad: &[] },
181 )
182 .map_err(|_| MnemoError::WrongPassphrase)?;
183 if plain.len() != KEY_LEN {
184 return Err(MnemoError::WrongPassphrase);
185 }
186 let mut dek = Zeroizing::new([0u8; KEY_LEN]);
187 dek.copy_from_slice(&plain);
188 Ok(dek)
189}